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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With