1

I wonder if there's any difference between waiting on a locked mutex and waiting on a locked semaphore, in terms of CPU-usage. According to the man pages, at both scenarios the thread blocks, meaning it is transferred to a waiting queue, thus not consuming CPU-time.

On the contrary, I did see a few places and answers that claim that waiting on a mutex causes busy-waiting, which means consuming CPU-time to no avail.

I'd appreciate if you could explain whether there's a difference or not.

Edit: My question was identified as a possible duplicate of this question, however, like I noted, I see opposite answers in some other places in this forum, that claim that waiting on a mutex is a busy-waiting.

Raz Moshe
  • 59
  • 1
  • 6
  • Possible duplicate of [Lock, mutex, semaphore... what's the difference?](https://stackoverflow.com/questions/2332765/lock-mutex-semaphore-whats-the-difference) – Bo Persson May 11 '18 at 10:45
  • 1
    In the ideal case, a thread would _never_ wait for a mutex. That can, of course, happen in reality, and that is why we _have_ mutexes; but in a well-designed program, a thread should never have to wait any longer than maybe a microsecond for a mutex. That is why some mutex implementations, when running on multi-CPU systems, will try spinning for some small amount of time before falling back to a true wait state. – Solomon Slow May 11 '18 at 14:54

1 Answers1

1

Surely this depends on the OS and compiler implementation that you have used.

However, since a mutex can be implemented as a version of a semaphore, then the worst case would be that the mutex performs as a semaphore. There would be no reason to code it less efficently.

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28