1.理解生产者和消费者问题
没有引入信号量时的生产者和消费者进程,什么情况下会出现结果不唯一?什么情况下会出现永远等待?
用信号解决生产者和消费者的同步与互斥,要求能自己写出来。
答:生产者进程和消费者进程对counter的交替操作会使其结果不唯一。
生产者进程和消费者进程的交替执行会导致进程永远等待,造成系统死锁。
2、哲学家吃面问题
semaphore fork[5];
for(int i=0; i<5;i++)
fork[i]=1;
cobegin
process philosopher_i( ){
while(ture){
think( );
P(fork[i]);
P(fork[(i+10%5]);
eat();
V(fork[i]);
V(fork[(i+10%5]);
}
}
coend
4.理发师问题
int waiting=0, chairs=n;
semaphore customers=0,barbers=0,mutex=1;
cobegin
process barbers() {
while(ture) {
P(customers);
P(mutex);
waiting--;
V(barbers);
V(mutex);
cuthair(); } }
process customer_i() {
P(mutex);
if(waiting<chairs) {
waiting++;
V(customers);
V(mutex);
P(barbers):
get_haircut();
}
else
V(mutex);
}
coend
6.某银行有人民币储蓄业务,由n个储蓄员负责。每个顾客进入银行后先取一个号,并且等着叫号。当一个储蓄人员空闲下来,就叫下一个号。请用P,V操作正确编写储蓄人员和顾客进程的程序。
答:semaphore mutex=A, customer_count=0:
main()
{
Cobegin
Customeri()
{
p(mutex);
取号码,进入队列;
v(mutex);
v(customer_count);
}
serversi()
{
while(A)
{
p(customer_count);
p(mutex);
从队列中取下一个号码;
v(mutex);
为该号码持有者服务;
}
end
Coend
7.下面是两个并发执行的进程。它们能正确运行吗?若不能请举例说明,并改正之。(5分)
parbegin
var X:integer;
process P1 process P2
var y,z:integer: var t,u:integer;
begin begin
x:=1; x:=0:
y:=0: t=0;
if x≥l then y:=y十1; if x≤l then t:=t+2;
z:=y; u:=t;
end; end;
parend.
答:能。
原文:https://www.cnblogs.com/zzj520/p/10821446.html