Advertisement
Guest User

Untitled

a guest
May 5th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. class RW_mutex{
  2.  
  3. public:
  4.     RW_mutex() : writers(0), readers(0), writing(false) {}
  5.  
  6.     void write_lock(){
  7.         std::unique_lock<std::mutex> lock(gate);
  8.         writers++;
  9.         while (writing || readers > 0){
  10.             room_empty.wait(lock);
  11.         }
  12.         writing = true;
  13.     }
  14.  
  15.     void read_lock(){
  16.         std::unique_lock<std::mutex> lock(gate);
  17.         while (writers > 0){
  18.             room_empty.wait(lock);
  19.         }
  20.         readers++;
  21.     }
  22.  
  23.     void write_unlock(){
  24.         std::unique_lock<std::mutex> lock(gate);
  25.         writers--;
  26.         writing = false;
  27.         room_empty.notify_all();
  28.     }
  29.  
  30.     void read_unlock(){
  31.         std::unique_lock<std::mutex> lock(gate);
  32.         readers--;
  33.         if (readers == 0) room_empty.notify_all();
  34.     }
  35.  
  36. private:
  37.     std::mutex gate;
  38.     std::size_t writers;
  39.     std::size_t readers;
  40.     std::condition_variable room_empty;
  41.     bool writing;
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement