Synchronization in C 0x Without Semaphores
C 0x introduces atomic variables and conditions, but lacks explicit semaphore support. This has raised concerns about how to effectively synchronize threads without using Boost's semaphore implementation.
One method involves utilizing a combination of mutexes and condition variables to create a custom-built semaphore. Consider the following example:
#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 implementation utilizes a mutex (mutex_) to guard access to the internal data and employs a condition variable (condition_) to signal waiting threads when a semaphore is released. The count_ member variable is initialized to zero, indicating an initially locked state.
To release a semaphore (i.e., make it available for acquisition), the release() method increments the count and notifies any waiting threads. To acquire a semaphore, the acquire() method waits until the count is non-zero. The try_acquire() method attempts to acquire the semaphore non-blockingly, returning true if successful or false otherwise.
This approach provides a simple and efficient way to implement semaphores in C 0x without using Boost. It is similar in functionality to POSIX semaphores, allowing threads to synchronize their execution and communicate events effectively.
The above is the detailed content of How Can I Implement Semaphores in C 0x Without Using Boost?. For more information, please follow other related articles on the PHP Chinese website!