Medium
notify_all on a single-slot resource pool
A resource pool holds exactly one available slot at a time. 50 threads are all blocked in acquire(), waiting for slotAvailable to become true. release() is called once. What actually happens with notify_all() here, and is it the right call to use?
main.cpp
std::mutex mtx;
std::condition_variable cv;
bool slotAvailable = true;
void acquire() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return slotAvailable; });
slotAvailable = false;
// ... use the one available slot ...
}
void release() {
{
std::lock_guard<std::mutex> lock(mtx);
slotAvailable = true;
}
cv.notify_all(); // wakes every one of the 50 waiters
}31 of 51 in Concurrency