OS

OS 中的 P-V 操作
生产者-消费者 && 哲学家 && 读者-写者 && 理发师-顾客

生产者-消费者

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
semaphore mutex = 1;
semaphore empty = n;
semaphore full = 0;

Producer(){
while(1){
produce;
P(empty);

P(mutex);
add to buffer;
V(mutex);

V(full);
}
}

Consumer(){
while(1){
P(full);

P(mutex);
remove from buffer;
V(mutex);

V(empty);
consume;
}
}

哲学家就餐

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
semaphore chop[5] = {1, 1, 1, 1, 1};
semaphore mutex = 1;

Pi(){
while(1){
think;

P(mutex);
P(chop[i]);
P(chop[(i+1)%5]);
V(mutex);

eat;

V(chop[i]);
V(chop[(i+1)%5]);
}
}

读者-写者

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
int count = 0;
semaphore mutex = 1;
semaphore rw = 1;
semaphore w = 1;

Writer(){
while(1){
// P(w); // 写优先信号
P(rw);
writing;
V(rw);
// V(w);
}
}

Reader(){
while(1){
// P(w); // 写优先信号
P(mutex);
if(count == 0)
P(rw);
count++;
V(mutex);
// V(w);

reading;

P(mutex);
count--;
if(count == 0)
V(rw);
V(mutex);
}
}

理发师-顾客

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
int waiting = 0;
int chairs = N;
semaphore customers = 0;
semaphore barbers = 0;
semaphore mutex = 1;

Barbers(){
while(1){
P(customers);
P(mutex);
waiting--;
V(barbers);
V(mutex);
cut hair;
}
}

Customes(){
P(mutex);
if(waiting < chairs){
waiting++;
V(customes);
V(mutex);
P(barbers);
get haircut;
}
else
V(mutex);
}
作者

Cheng

发布于

2018-10-28

更新于

2022-08-06

许可协议

评论