Does WaitForSingleObject give up a thread's time slice?
Asked Answered
K

2

5

I'm making a win32 program in C.

When you have multiple threads running, and one of the threads is waiting for an event (using WaitForSingleObject() for example), does that thread still get its full CPU time slice?

Stated differently, does the operating system know that the thread doesn't need its time slice until one of the events is signalled?

Killie answered 13/11, 2010 at 0:50 Comment(1)
Yes, OS knows it. That's the whole point of thread scheduling - run only those threads that are actually doing something.Gibber
G
9

Yes -- the thread is blocked until whatever it's waiting on becomes signaled. The thread won't be scheduled to run while it's blocked, so other threads get all the CPU time.

Note that time slices don't enter into it much though. A thread can give up execution in the middle of a time slice, and (for example) if what it's waiting on becomes signaled quickly, it might start executing again before its original time slice expires. When something is signaled, a thread that's waiting on it can wake up immediately, not necessarily waiting for the end of a time slice (e.g., if the thread that was waiting has higher priority than the thread that was running).

Georgiana answered 13/11, 2010 at 1:2 Comment(2)
"Yes -- the thread is blocked until whatever it's waiting on becomes signaled." If the object is already signaled when WaitForSingleObject is called, does the thread relinquish the remainder of its time slice?Papaverine
At least in my testing, if a object is already signaled when you call WaitForSingleObject, it simply returns and the thread continues execution. It does involve a switch to kernel mode and back, so it can take something like a microsecond. But no, just calling WFSO/WFMO doesn't mean the thread is yielding the rest of its timeslice.Georgiana
E
2

If the object you're waiting on is not already signalled, the thread will yield the rest of its timeslice and go to sleep until the object is signalled.

Everett answered 13/11, 2010 at 0:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.