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