zoukankan      html  css  js  c++  java
  • 面试题:读写锁实现

    代码中存在bug,暂时无法修复

     1 #include <condition_variable>
     2 #include <mutex>
     3 
     4 class rw_lock {
     5 private:
     6     std::mutex mtx;
     7     std::condition_variable cv1; //block by a writer
     8     std::condition_variable cv2; //block by a reader
     9     int waiteForWrite;
    10     int waiteForRead;
    11     int reading;
    12     enum {
    13         RLOCK, WLOCK, NOLOCK
    14     };
    15     int state;
    16 public:
    17     //first write.
    18     void r_lock() {
    19         std::unique_lock<std::mutex> lck(mtx);
    20         while (state == WLOCK || waiteForWrite != 0) {
    21             waiteForRead++;
    22             cv1.wait(lck);
    23         }
    24         reading++;
    25         state = RLOCK;
    26     }
    27 
    28     void r_unlock() {
    29         std::unique_lock<std::mutex> lck(mtx);
    30         reading--;
    31         if (reading == 0) {
    32             state = NOLOCK;
    33             cv2.notify_all();
    34         }
    35     }
    36 
    37     //request write lock
    38     void w_lock() {
    39         std::unique_lock<std::mutex> lck(mtx);
    40         while (state == RLOCK || state == WLOCK) {
    41             waiteForWrite++;
    42             cv2.wait(lck);
    43         }
    44         state = WLOCK;
    45     }
    46 
    47     void w_unlock() {
    48         std::unique_lock<std::mutex> lck(mtx);
    49         state = NOLOCK;
    50         cv1.notify_all();
    51     }
    52 
    53 };
  • 相关阅读:
    OO第三单元总结
    oo第二单元总结
    oo第一单元总结
    OO助教工作总结
    当QSY遇上XL尺码的小黄衫
    终点亦是起点
    敏捷开发规范化
    Beta阶段性总结
    需求存在,功能存在——Alpha阶段性总结
    Gitlab Burndown Chart
  • 原文地址:https://www.cnblogs.com/wxquare/p/7407281.html
Copyright © 2011-2022 走看看