Advertisement
MystMe

Untitled

Apr 2nd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <rwlock_traits.hpp>
  4. #include <tpcc/stdlike/condition_variable.hpp>
  5.  
  6. #include <mutex>
  7.  
  8. namespace tpcc {
  9. namespace solutions {
  10.  
  11. class ReaderWriterLock {
  12.  public:
  13.  
  14.   // Reader section
  15.   void ReaderLock() {
  16.     std::unique_lock<std::mutex> lock (mutex_);
  17.     while(write_acquire_ > 0) {
  18.       cond_var_.wait(lock);
  19.     }
  20.     readers_++;
  21.   }
  22.  
  23.   void ReaderUnlock() {
  24.     std::unique_lock<std::mutex> lock (mutex_);
  25.     readers_--;
  26.     cond_var_.notify_all();
  27.   }
  28.  
  29.   // Writer section
  30.   void WriterLock() {
  31.     std::unique_lock<std::mutex> lock (mutex_);
  32.     write_acquire_++;
  33.     while(readers_ > 0 || write_) {
  34.       cond_var_.wait(lock);
  35.     }
  36.     write_ = true;
  37.   }
  38.  
  39.   void WriterUnlock() {
  40.     std::unique_lock<std::mutex> lock (mutex_);
  41.     write_acquire_--;
  42.     write_ = false;
  43.     cond_var_.notify_all();
  44.   }
  45.  
  46.   private:
  47.     bool write_{false};
  48.     size_t write_acquire_{0};
  49.     size_t readers_{0};
  50.  
  51.     std::mutex mutex_;
  52.     tpcc::condition_variable cond_var_;
  53. };
  54.  
  55. } // namespace solutions
  56. } // namespace tpcc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement