Can You Use Semaphores in C 0x?
Semaphore-based synchronization is essential for thread communication. In the absence of semaphores in C 0x, it seems like a deadlock.
Semaphore Emulation with Mutex and Condition Variables
Fortunately, a semaphore can be recreated using a mutex and a condition variable. Here's a straightforward implementation:
#include <mutex> #include <condition_variable> class semaphore { std::mutex mutex_; std::condition_variable condition_; unsigned long count_ = 0; // Initialized as locked. public: void release() { std::lock_guard<decltype(mutex_)> lock(mutex_); ++count_; condition_.notify_one(); } void acquire() { std::unique_lock<decltype(mutex_)> lock(mutex_); while(!count_) // Handle spurious wake-ups. condition_.wait(lock); --count_; } bool try_acquire() { std::lock_guard<decltype(mutex_)> lock(mutex_); if(count_) { --count_; return true; } return false; } };
This emulation provides the fundamental behaviors of semaphores:
The above is the detailed content of Can C 0x Semaphores Be Emulated Using Mutexes and Condition Variables?. For more information, please follow other related articles on the PHP Chinese website!