SHARE
TWEET

Untitled

a guest May 25th, 2019 103 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. template<typename T>
  2. class Counter {
  3. private:
  4.     std::atomic<T> counter_;
  5.     twist::mutex mtx_;
  6.     twist::conditional_variable cv_is_zero_;
  7. public:
  8.     explicit Counter(T init_value = 0) : counter_(init_value) {};
  9.  
  10.     void Increment() {
  11.         auto locker = twist::LockUnique(mtx_);
  12.         counter_.fetch_add(1);
  13.         if (!counter_)
  14.             cv_is_zero_.notify_all();
  15.     }
  16.  
  17.     void Decrement() {
  18.         auto locker = twist::LockUnique(mtx_);
  19.         counter_.fetch_sub(1);
  20.         if (!counter_)
  21.             cv_is_zero_.notify_all();
  22.     }
  23.  
  24.     void AwaitZero() {
  25.         auto locker = twist::LockUnique(mtx_);
  26.         while (counter_ != 0) {
  27.             cv_is_zero_.wait(locker);
  28.         }
  29.     }
  30. };
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