面试题:读写锁实现

代码中存在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 };

 

转载于:https://www.cnblogs.com/wxquare/p/7407281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值