daily pastebin goal
23%
SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct WaitingNode {
  2.     std::condition_variable cv;
  3.     bool released = false;
  4. };
  5.  
  6. class Semaphore {
  7. public:
  8.     explicit Semaphore(int count) : count_(count) {
  9.     }
  10.  
  11.     void Leave() {
  12.         std::unique_lock<std::mutex> lock(mutex_);
  13.         ++count_;
  14.         if (!waiting_queue_.empty()) {
  15.             waiting_queue_.front().released = true;
  16.             waiting_queue_.front().cv.notify_one();
  17.         }
  18.     }
  19.  
  20.     void Enter() {
  21.         std::unique_lock<std::mutex> lock(mutex_);
  22.         if (count_ == 0 || !waiting_queue_.empty()) {
  23.             waiting_queue_.emplace_back();
  24.             auto& wnode = waiting_queue_.back();
  25.             wnode.cv.wait(lock, [&wnode] { return wnode.released; });
  26.             waiting_queue_.pop_front();
  27.         }
  28.         --count_;
  29.     }
  30.  
  31. private:
  32.     std::mutex mutex_;
  33.     int count_ = 0;
  34.     std::list<WaitingNode> waiting_queue_;
  35. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top