2
votes

I would like to understand how 'wait' on a thread is actually working ? Is there an endless loop behind the scene (does not sound resonable) ?

For example in MSDN/MFC manual page for 'WaitForSingleObject' function it says

The WaitForSingleObject function checks the current state of the specified object. If the object's state is nonsignaled, the calling thread enters the wait state until the object is signaled or the time-out interval elapses. (http://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx)

What is this "wait state"? How does the thread 'wake up' i.e. how rising an event or signale an object cause the thread to run again? Who checks the synchronization object and how often?

Thank you

1

1 Answers

4
votes

This is handled by the OS thread scheduler.

When a thread waits on something, the OS creates a link from the object it's waiting on back to the waiting object. When the state of the object being waited on changes, the scheduler looks through the objects that are waiting on it. If the state change un-blocks any of those, then it marks them as un-blocked, so they become eligible for scheduling.

The scheduler then has algorithms to choose which threads that are eligible for scheduling will actually be scheduled to run. The exact details change between OSes (and even between versions of the same OS), but based on what you asked, I'd guess you probably don't care much about that right now.

The bottom line is that once a thread blocks like this, (virtually) no CPU time is expended on seeing whether it can run again. Rather than going through all blocked threads, and seeing if the situation has changed so any of them can run, it looks only at the changes in situation, and when those happen it figures out which threads that will allow to run.

Of course, it's also possible that at least in theory some OS could work differently from this--but Windows definitely does work pretty much as described above, and most other typical systems (e.g., Linux, *BSD, MacOS) are pretty similar in this respect.