读者写者问题

经典读者写者问题

读者写者问题

1、读者优先
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
int readcount=0; 
semaphore RCSignal=1, fileSrc=1;
// RCSignal readcount修改互斥量
// fileSrc 文件资源互斥量:实现读者优先

// 读者进程:
P(RCSignal);
readcount++;
if (readcount == 1)
P(fileSrc);
V(RCSignal);
// ...
// reading is performed
// ...
P(RCSignal);
readcount--;
if (readcount == 0)
V(fileSrc);
V(RCSignal);

// 写者进程:
P(fileSrc);
//...
//writing is performed
//...
V(fileSrc);
2、写者优先
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
int readcount=0, writecount=0; 
semaphore RCSignal=1, WCSignal=1, read=1, fileSrc;
// RCSignal readcount修改互斥量
// WCSignal writecount修改互斥量
// read 实现写者优先:拦截读者
// fileSrc 文件资源互斥量:保护剩余读者(拦截写者),以及写者唯一

// 读者进程:
P(read);
P(RCSignal);
readcount++;
if(readcount == 1 )
P(fileSrc);
V(RCSignal);
V(read);
// ...
// reading is performed
// ...
P(RCSignal);
readcount--;
if (readcount == 0 )
V(fileSrc);
V(RCSignal);

// 写者进程:
P(WCSingal);
writecount++;
if (writecount == 1 )
P(read);
V(WCSingal);
P(fileSrc);
// writing is performed
V(fileSrc);
P(WCSingal);
writecount --;
if (writecount == 0)
V(read);
V(WCSingal);
参考资料

https://www.bilibili.com/video/av21593625 https://blog.csdn.net/c1194758555/article/details/52805918 https://blog.csdn.net/william_munch/article/details/84256690 (有问题?)