c++c++20mutexsemaphore

Why use a mutex and not a semaphore?


Looking in cppreference, it seems to imply a std::binary_semaphore may be more efficient than a std::mutex.

Is there any reason not to use a std::binary_semaphore initialized to 1 instead of a std::mutex?


Solution

  • One big advantage that's not mentioned in the other answers is priority inheritance.

    If a higher priority thread (for instance an interactive thread instead of a background one) tries to lock a mutex while a lower priority thread holds it, the lower priority thread will be temporarily upgraded so it can get its job done quick and release the lock to let the high priority thread run.

    Since a semaphore can be "released" by any thread, there's no clear thread to increase the priority of and therefore priority inheritance does not work with them. So using a mutex instead of a semaphore is better for responsiveness too.