1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
| #ifndef _PREAD_WRITE_LOCK_H_
| #define _PREAD_WRITE_LOCK_H_
|
| #include "usg_common.h"
| #include "psem.h"
| class PReadWriteLock {
| private:
| unsigned int readCount = 0;
| sem_t countMutex;
| sem_t writeMutex;
|
|
| public:
| PReadWriteLock() {
| if (sem_init(&countMutex, 1, 1) == -1)
| err_exit(errno, "PReadWriteLock sem_init");
|
| if (sem_init(&writeMutex, 1, 1) == -1)
| err_exit(errno, "PReadWriteLock sem_init");
| }
|
| void lockRead() {
| //readCount是共享变量,所以需要实现一个锁来控制读写
| //synchronized(PReadWriteLock.class){}
| psem_wait(&countMutex);
| //只有是第一个读者,才将写锁加锁。其他的读者都是进行下一步
| if(readCount == 0){
| psem_wait(&writeMutex);
|
| }
| ++readCount;
| psem_post(&countMutex);
| }
|
|
| void unlockRead(){
|
| psem_wait(&countMutex);
| readCount--;
| //只有当读者都读完了,才会进行写操作
| if(readCount == 0){
| psem_post(&writeMutex);
| }
| psem_post(&countMutex);
| }
|
|
| void lockWrite(){
| psem_wait(&writeMutex);
| }
|
| void unlockWrite(){
| psem_post(&writeMutex);
| }
| };
|
| #endif
|
|