3 ms·
> the WaitForObject won't wake up any sooner than Sleep(1) will. Only a real proper hardware interrupt could wake up quicker - but that requires special hardwar
by jlokier 6y ago
> the WaitForObject won't wake up any sooner than Sleep(1) will. Only a real proper hardware interrupt could wake up quicker - but that requires special hardware that just wasn't available in that scenario. If it's easier to think about that way, then please assume I said that WaitForObject "sleeps" way more than necessary due to the low timer resolution on Windows.
Above is not correct.
SetEvent/WaitForSingleObject takes a few microseconds to wake the thread. Not milliseconds, microseconds.
WaitForSingleObject doesn't use a timer if you set infinite timeout.
It does not "sleep more than necessary due to the low timer resolution", because it does not use the timer.
Even if you set a timeout, it doesn't use the timer when the wake is triggered by SetEvent. The wake is immediate.
Wake triggered by SetEvent in a different thread doesn't use interrupts or need special hardware. It's purely kernel scheduling inside Windows.
For a real-world measurement, see for example:
>> "Windows event object was used but it takes 6-7us from SetEvent() to WaitForSingleObject() return on my machine
The person is annoyed that it takes 6-7 microseconds, and they want to get it lower.
Here's a Microsoft example of how to have one thread wake another:
https://docs.microsoft.com/en-us/windows/win32/sync/using-event-objects https://docs.microsoft.com/en-us/windows/win32/sync/using-ev...
There are other ways for one thread to quickly wake another thread on Windows, but SetEvent/WaitForSingleObject is the easiest in a general purpose thread.
What I suspect happened in tests where it appeared that "WaitForObject "sleeps" way more than necessary" is that there was a race condition in the event trigger/wakeup logic between the two threads, causing the worker thread to depend on timeout behaviour of WaitForSingleObject instead of being woken reliably by SetEvent. That is is actually a very common bug in this kind of wakeup logic, and you have to understand race conditions to solve it. When the race condition is solved, SetEvent wakeups become consistently fast.