Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will WaitForSingleObject cause a context switch when waiting with a timeout time of zero?

Will WaitForSingleObject (or WaitForMultipleObjects) cause a context switch when waiting for an event with a timeout time of zero? (Sleep(0) will yield a threads time-slice immediately as far as I know.)

Now, regarding WaitForSingle|MultipleObject and Event handles. If WaitFor*Object actually needs to wait, it would obviously yield the rest of its time-slice. However, there are two cases where the API does not need to wait:

  • Either the event is signalled, in which case it can return with WAIT_OBJECT_0
  • Or the state of the event doesn't matter as I specified a wait time of zero, in which case it can return immediately, either with WAIT_OBJECT_0 or WAIT_TIMEOUT

Now, given this, will WaitForSingleObject cause a thread context switch if a timeout time of zero is supplied?

like image 454
Martin Ba Avatar asked Nov 17 '10 10:11

Martin Ba


2 Answers

Based on the Windows Research Kernel and some simple reverse-engineering of KeWaitForSingleObject, the answer is no. Looking at the WRK, the internal timer's due time is checked before KiSwapThread is called, making sure the function returns immediately if the object isn't signaled.

like image 71
wj32 Avatar answered Oct 25 '22 08:10

wj32


Now it seems I kind of found an answer while writing up the question -- here's what I assume from the available docs:

The MSDN states the following:

dwMilliseconds [in]

The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the specified objects are signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the specified objects are not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the specified objects are signaled.

I would take this to imply that it also does not enter a wait state if the objects are signaled and I would interpret "does not enter a wait state" as "no context switch happens".

like image 44
Martin Ba Avatar answered Oct 25 '22 08:10

Martin Ba