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
| #ifndef _SV_READ_WRITE_LOCK_H_
| #define _SV_READ_WRITE_LOCK_H_
|
| #include "usg_common.h"
| #include "svsem.h"
| class SvReadWriteLock {
| private:
| unsigned int readCount = 0;
| int countMutex;
| int writeMutex;
|
|
| public:
| SvReadWriteLock() {
| countMutex = svsem_get(IPC_PRIVATE, 1);
| writeMutex = svsem_get(IPC_PRIVATE, 1);
| }
|
| void lockRead() {
| //readCount是共享变量,所以需要实现一个锁来控制读写
| //synchronized(ReadWriteLock.class){}
| svsem_wait(&countMutex);
| //只有是第一个读者,才将写锁加锁。其他的读者都是进行下一步
| if(readCount == 0){
| svsem_wait(&writeMutex);
|
| }
| ++readCount;
| svsem_post(&countMutex);
| }
|
|
| void unlockRead(){
|
| svsem_wait(&countMutex);
| readCount--;
| //只有当读者都读完了,才会进行写操作
| if(readCount == 0){
| svsem_post(&writeMutex);
| }
| svsem_post(&countMutex);
| }
|
|
| void lockWrite(){
| svsem_wait(&writeMutex);
| }
|
| void unlockWrite(){
| svsem_post(&writeMutex);
| }
| };
|
| #endif
|
|