According to the C++20 semaphore docs, semaphores can be used in a similar manner to condition variables:
Semaphores are also often used for the semantics of signalling/notifying rather than mutual exclusion, by initializing the semaphore with 0 and thus blocking the receiver(s) that try to acquire(), until the notifier "signals" by invoking release(n). In this respect semaphores can be considered alternatives to std::condition_variables, often with better performance.
Emphasis mine. I've used semaphores in this manner in Java and Swift in the past, but in C++, I've normally resorted to using std::condition_variable
for this signal/notify pattern. With C++20, I now have access to std::binary_semaphore
, and I'm wondering what the difference is.
When does a semaphore (in particular, std::binary_semaphore
) have better performance than using std::condition_variable
in the same manner, and why?
condition_variable
requires explicitly using amutex
whilebinary_semaphore
does not should clue you into the difference.