//https://gist.github.com/yohhoy/2156481
//reference 1 :
//http://stackoverflow.com/questions/13099660/c11-why-does-stdcondition-variable-use-stdunique-lock
/* http://stackoverflow.com/questions/16350473/why-i-need-stdcondition-variable
    while (!is_ready)
    {
        cv.wait(lk);
        if (!is_ready)
            std::cout << "Spurious wake up!\n";
    }
*/


//google : condition_variable wait lambda

#include <mutex>
#include <condition_variable>
// binary semaphore
class binsem {
public:   
    explicit binsem(int init_count = count_max)     
    : count_(init_count) {}    
 // P-operation / acquire   
 void wait()   
 {       
     std::unique_lock<std::mutex> lk(m_);       
  cv_.wait(lk, [this]{ return 0 < count_; });
  --count_;   
 }   
 bool try_wait()   
 {       
     std::lock_guard<std::mutex> lk(m_);       
  if (0 < count_)
  {           
      --count_;           
   return true;       
  } else
  {           
      return false;       
  }   
 }
 // V-operation / release   
 void signal()   
 {       
     std::lock_guard<std::mutex> lk(m_);
            
     //if (count_ < count_max)
  //{
      ++count_;
   cv_.notify_one();       
  //}   
 }    
 // Lockable requirements   
 void lock() { wait(); }   
 bool try_lock() { return try_wait(); }   
 void unlock() { signal(); }
private:   
    static const int count_max = 1;   
 int count_;   
 std::mutex m_;   
 std::condition_variable cv_;
};

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()