Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 mutexes and semaphores do that? Doesn't they interfere with the process scheduler decisions?

like image 651
Boolean Avatar asked Jan 21 '23 13:01

Boolean


1 Answers

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

  1. ask the scheduler to wake one of the waiting threads at the scheduler's discretion, or

  2. 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.

like image 192
Anthony Williams Avatar answered Jan 30 '23 00:01

Anthony Williams