介绍
采用python多线程模拟理发师问题,初始的时候需要设置理发店可供等待顾客坐的椅子数。
理发师问题用P、V操作描述如下:
信号量mutex表示waiting的互斥操作权,初值为1
信号量bchair表示理发椅互斥,初值为1
信号量wchair表示等待椅资源,初值为n
信号量ready和finish进行理发师和顾客间通信,初值为0
int waiting = 0;//顾客数(正在理发的+等待的,最多N+1人)
semphore mutex = 1, bchair = 1, wchair = n, ready = finish = 0;
int main(){
cobegin
barber();
customer();
coend
}
barber(){
while (true){
P(ready);
理发;
V(finish);
}
}
customer(){
P(mutex)
if (waiting <= n){
waiting++;
V(mutex);
}
else{
V(mutex);
没有位置,离开;
}
P(wchair);
P(bchair);
V(wchair);
V(ready);
P(finish);
V(bchair);
P(mutex);
waiting–;
V(mutex);
}
按照,以上P、V操作编写代码,具体实现步骤在此不做赘述,代码中有适当注释。
试验结果:
由于程序一直在运行,因此只截取部分输出结果



相关阅读
Python|页面置换模拟程序设计
Python|银行家算法
Python|独占设备的分配和回收模拟
Python|模拟文件系统
Python|进程调度算法
Python|分页管理方式下存储分配情况模拟
Python|Windows下实现经典进程同步问题——理发师问题
Python|模拟实现动态分区存储管理
完整代码
import threading
import time
# 理发开始信号量
ready = threading.Semaphore(0)
# 理发结束信号量
finish = threading.Semaphore(0)
# 互斥信号量
mutex = threading.Lock()
# 初始理发人数
wait_customer = 0
# 等待椅子是互斥的
wchair = threading.Lock()
# 理发椅是互斥的
barchair = threading.Lock()
# 椅子的个数
CHAIRS = 6
# 编号
counter = 0
# 等待队列
wchair_list = []
#
in_cut = 0
def customer():
# 顾客进程
global wait_customer, CHAIRS, mutex, wchair, finish, barchair, ready, counter, in_cut
time.sleep(2)
# 进入临界区,修改等待人数
mutex.acquire()
if wait_customer <= CHAIRS:
wait_customer += 1
counter += 1
print('顾客{}来了'.format(counter))
wchair_list.append(counter)
print('顾客的当前人数为:', wait_customer)
print('等待队列为:', wchair_list)
mutex.release()
# 等待椅子资源是否可用
wchair.acquire()
# 等待理发
barchair.acquire()
# 可以理发,释放等待椅子资源
try:
in_cut = wchair_list.pop(0)
except:
pass
wchair.release()
print('顾客{}坐上了理发椅'.format(in_cut))
print('剩余等待队列为:', wchair_list)
# 向理发师发送信号
ready.release()
# 等待理发完毕
finish.acquire()
# 释放理发椅资源
print('顾客{}离开了理发椅,美滋滋地走出店门!'.format(in_cut))
barchair.release()
# 修改顾客人数
mutex.acquire()
wait_customer -= 1
mutex.release()
else:
counter += 1
print('顾客{}来了'.format(counter))
print('等待人数已满,没有座位,顾客{}离开'.format(counter))
mutex.release()
def barber():
# 理发师进程
print('理发店开张了!')
print('--------------------------')
global wait_customer, CHAIRS, mutex, ready, finish
while True:
if wait_customer == 0:
print('没有顾客,睡觉!')
time.sleep(1)
# 等待顾客发出请求
ready.acquire()
cut_hair()
# 理发完毕
finish.release()
def cut_hair():
print('理发师正在理发!')
time.sleep(2)
print('理发完毕!', end=' ')
if __name__=='__main__':
CHAIRS = int(input('请输入理发店可供等待顾客坐的椅子数:'))
t1 = threading.Thread(target=barber)
t1.start()
t1.join(1)
while True:
try:
time.sleep(0.5)
t2 = threading.Thread(target=customer)
t2.start()
t2.join(1)
except:
print('出错了!')
本文通过Python多线程实现经典的进程同步问题——理发师问题。使用信号量与锁来模拟理发店中的顾客等待及理发过程,包括顾客到达、等待、理发及离开等状态变化。

1万+

被折叠的 条评论
为什么被折叠?



