Is it true that C++0x will come without semaphores? There are already some questions on Stack Overflow regarding the use of semaphores. I use them (posix semaphores) all the
You can easily build one from a mutex and a condition variable:
#include
#include
class semaphore
{
private:
std::mutex mutex_;
std::condition_variable condition_;
unsigned long count_ = 0; // Initialized as locked.
public:
void notify() {
std::lock_guard lock(mutex_);
++count_;
condition_.notify_one();
}
void wait() {
std::unique_lock lock(mutex_);
while(!count_) // Handle spurious wake-ups.
condition_.wait(lock);
--count_;
}
bool try_wait() {
std::lock_guard lock(mutex_);
if(count_) {
--count_;
return true;
}
return false;
}
};