哲学家进餐问题
(1)了解操作系统进程同步的基本概念和准则。
(2)理解信号量机制及P、V操作含义。
(3)了解经典进程同步问题,掌握信号量方法解决进程同步问题的方法。
import numpy as np
资源=[1,1,1,1,1]
请求=[1,1,1,1,1]
程序=[0,0,0,0,0]
队列=[]
def P(i):
请求[i]=请求[i]-1
def V(i):
资源[i]=1
请求[i]=1
def 程序本恶(i):
# print(i)
P(i)
P((i+1)%5)
if(min(请求)==-1):
请求[i]=资源[i]
请求[(i+1)%5]=资源[(i+1)%5]
队列.append(i)
print("阻塞程序"+str(i))
else:
资源[i]=请求[i]
资源[(i+1)%5]=请求[(i+1)%5]
# print(队列)
print("运行程序"+str(i))
V((i+1)%5)
V(i)
程序[i]=1
# print(i)
队列.pop(队列.index(i))
# print("uuuuuu"+str(队列.index(i)))
# print(队列)
# print(i)
# print(队列)
def 分配程序():
while(min(程序)==0):
for i in range(5):
if 程序[i]==0:
if np.random.rand(1)[0]<0.3:
# print(6666)
# print(i)
队列.append(i)
# print(队列)
for i in 队列:
print(队列)
程序本恶(i)
分配程序()