How does mutex or semaphore wake up processes?
I read that mutexes and semaphores maintain a list of waiting processes and wake them up when the current thread completes the critical section. How do mutex开发者_Python百科es and semaphores do that? Doesn't they interfere with the process scheduler decisions?
The waiting and waking up is typically done in cooperation with the scheduler. A mutex implementation that forces a specific one of the waiting threads to wake is typically considered to be a poor implementation.
Instead, the mutex or semaphore will notify the scheduler that a thread is waiting, and thus to take it off the "ready to run" list. Then, when the mutex is unlocked or the semaphore signalled, the implementation will either
ask the scheduler to wake one of the waiting threads at the scheduler's discretion, or
notify the scheduler that all the waiting threads are ready to run, and then have logic on the waiting threads so that all but the first one to be woken by the scheduler go back to sleep again.
The former is the preferred implementation choice, but is not always available. The second is often dubbed a "thundering herd" approach: if there are 1000 threads waiting then all 1000 are woken (a big thundering herd of threads), only for 999 to go back to sleep. This is wasteful of CPU resources, and implementations will avoid it where possible.
This depends largely on the implementation. When speaking of these things, we usually refer to threads, which may have operating system support, or may be implemented entirely in the language, and thus do not even interact with the O/S for thread support.
They can also refer to processes, however, but these implementations usually require complex message passing patterns, in addition to some O/S support for process management.
Yes, the simple explanation is that any waiting process (whether semaphore or I/O) is taken off the scheduler's run queue until its wait condition is satisfied.
精彩评论