c++ - C++0x has no semaphores? How to synchronize threads? -


is true c++0x come without semaphores? there questions on stack overflow regarding use of semaphores. use them (posix semaphores) time let thread wait event in thread:

void thread0(...) {   dosomething0();    event1.wait();    ... }  void thread1(...) {   dosomething1();    event1.post();    ... } 

if mutex:

void thread0(...) {   dosomething0();    event1.lock(); event1.unlock();    ... }  void thread1(...) {   event1.lock();    dosomethingth1();    event1.unlock();    ... } 

problem: it's ugly , it's not guaranteed thread1 locks mutex first (given same thread should lock , unlock mutex, can't lock event1 before thread0 , thread1 started).

so since boost doesn't have semaphores either, simplest way achieve above?

you can build 1 mutex , condition variable:

#include <mutex> #include <condition_variable>  class semaphore { private:     std::mutex mutex_;     std::condition_variable condition_;     unsigned long count_ = 0; // initialized locked.  public:     void notify() {         std::unique_lock<decltype(mutex_)> lock(mutex_);         ++count_;         condition_.notify_one();     }      void wait() {         std::unique_lock<decltype(mutex_)> lock(mutex_);         while(!count_) // handle spurious wake-ups.             condition_.wait(lock);         --count_;     }      bool try_wait() {         std::unique_lock<decltype(mutex_)> lock(mutex_);         if(count_) {             --count_;             return true;         }         return false;     } }; 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -