MystMe

Untitled

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