SHARE
TWEET

Untitled

a guest May 25th, 2019 93 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ReadLock -- ReadUnlock
  2. // WriteLock -- WriteUnlock
  3. // read priority
  4.  
  5. private:
  6.     std::condition_variable can_read_, can_write_;
  7.     std::atomic<int> readers_;
  8.     std::atomic<bool> locked_;
  9.  
  10. public:
  11.     WriteLock() {
  12.         std::unique_lock<std::mutex> lock;
  13.         while(locked_) {
  14.             can_write_.wait(lock);
  15.         }
  16.         locked_.store(true);
  17.         while (readers_.load() != 0)
  18.             can_write_.wait(lock);
  19.     }
  20.  
  21.     ReadLock() {
  22.         std::unique_lock <std::mutex> lock;
  23.         while(locked_) {
  24.             can_read_.wait(lock);
  25.         }
  26.         readers_.fetch_add(1);
  27.     }
  28.  
  29.     WriteUnlock() {
  30.         if (readers_.load() != 0) {
  31.             can_read_.notify_one();
  32.         } else {
  33.             can_write_.notify_one();
  34.         }
  35.         locked_.store(false);
  36.     }
  37.  
  38.     ReadUnlock() {
  39.         if (readers_.fetch_add(-1) != 0) {
  40.             can_read_.notify_one();
  41.         } else {
  42.             can_write_.notify_one();
  43.         }
  44.     }
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