一、实验目的
1、 加深对进程概念的理解,明确进程和程序的区别。
2、 认识进程并发执行的实质
3、 掌握信号通信机制,实现进程之间通过信号实现互斥与同步的方法。
二、实验内容
桌子上有一只盘子,最多可容纳两个水果,每次只能放入或者取出一个水果。爸爸专门向盘子中放苹果,妈妈专门向盘子中放橘子,儿子专门等待吃盘子中的橘子,女儿专门等吃盘子中的苹果。试编程实现爸爸、妈妈、儿子、女儿四个人之间的同步。
(1)水果、盘子均通过导入图片来实现可视化;
(2)放水果、拿水果均有动画显示,包括把水果拿到手上去放、放完空手回来等均通过的动画予以展示;
(3)执行顺序由并发控制机制决定,而非通过延时实现;
(4)要求界面美观、动作流畅。
三、实验要求
1、 写出程序,并调试程序,要给出测试数据和实验结果。
2、 整理上机步骤,总结经验和体会。
3、 完成实验报告和上交程序。
四、实验代码
2.1.py 进程控制吃水果
import time import random from multiprocessing import Process, JoinableQueue import multiprocessing as mp """ Process常用属性与方法: name:进程名 pid:进程id run(),自定义子类时覆写 start(),开启进程 join(timeout=None),阻塞进程 terminate(),终止进程 is_alive(),判断进程是否存活 task_done()方法 JoinableQueuea: 参考:https://blog.csdn.net/qq_36811322/article/details/88295637 比原先队列多了一个方法task_done():当队列中的数据处理完会反馈给队列! join()方法:阻塞方法,当队列中的数据都task_done()完成后,join()就结束了 """ def producer(q,name: str, food: str,l,g_num,g_apple,g_orange): l.acquire() # 锁住 time.sleep(random.uniform(0.1, 0.8)) if food == '苹果': if g_num.value < 2 and g_apple.value < 1: g_apple.value = g_apple.value+1 # 设置为全局变量,使用方法对外部产生影响 g_num.value = g_num.value+1 q.put((1, food)) print(f'{name}把{food}放到盘子里') print(f'现在桌子上有{g_apple.value}份苹果,{g_orange.value}份橘子!') elif food == '橘子': if g_num.value < 2 and g_orange.value < 1: g_orange.value = g_orange.value+1 g_num.value = g_num.value+1 q.put((1, food)) print(f'{name}把{food}放到盘子里') print(f'现在桌子上有{g_apple.value}份苹果,{g_orange.value}份橘子!') # else: # q.join() # q.task_done() l.release() # 释放 def consumer(q1,q, name: str,food:str,l,g_capacity,g_num,g_apple,g_orange): res = q1.get() print(res) #(1, '苹果') time.sleep(random.uniform(0.1, 0.5)) l.acquire() # 锁住 if (food=='橘子'or food=='苹果') and (res[1]=='橘子' or res[1]=='苹果'): g_num.value = g_num.value - 1 if food == '橘子': g_orange.value = g_orange.value-1 else: g_apple.value = g_apple.value - 1 print(f'{name}从桌上拿走了{food}') print(f'现在桌子上有{g_apple.value}份苹果,{g_orange.value}份橘子!') # q.task_done() # else: # q.join() l.release() # 释放 if __name__ == '__main__': l = mp.Lock() # 定义一个进程锁 g_capacity = mp.Value('i', 2) # 最大容量 g_num = mp.Value('i', 0) # 当前个数 g_apple = mp.Value('i', 0) # 苹果个数 g_orange = mp.Value('i', 0) # 橘子个数 while True: q1 = JoinableQueue() p1 = Process(target=producer, args=(q1, '爸爸', '苹果',l,g_num,g_apple,g_orange)) # print(p1) p1.start() # print(g_apple.value) q2 = JoinableQueue() p2 = Process(target=producer, args=(q2, '妈妈', '橘子',l,g_num,g_apple,g_orange)) p2.start() q3 = JoinableQueue() c1 = Process(target=consumer, args=(q1,q3, '儿子','橘子',l,g_capacity,g_num,g_apple,g_orange)) c1.daemon = True c1.start() q4 = JoinableQueue() c2 = Process(target=consumer, args=(q2,q4, '女儿','苹果',l,g_capacity,g_num,g_apple,g_orange)) c2.daemon = True c2.start() # p1.join() # p1和p2的阻塞是为了让数据都生产结束,这样队列才能反馈处理结果 # p2.join() # q.join() # 当队列数据反馈都数据结束后,阻塞才会结束
Test2.py 进程控制吃水果&可视化界面
import threading,time,pygame,sys # 传入文件的 URL 注意此处的 URL 必须为绝对路径,否则会报错 background_image_filename = 'backgrand.jpg' apple_image_filename = 'apple.png' orange_image_filename = 'orange.png' mom_image_filename = 'mom.png' father_image_filename = 'dad.png' son_image_filename = 'boy.png' daughter_image_filename = 'girl.png' dad_hand_image_filename = 'hand.png' mom_hand_image_filename = 'hand.png' son_hand_image_filename = 'hand.png' daughter_hand_image_filename = 'hand.png' # 初始化pygame,为使用硬件做准备 pygame.init() # 放橘子和苹果时的 位置 one_size = (600, 400) # 列 宽 two_size = (900, 500) dad_size = (100, 100) mom_size = (100, 1300) son_size = (700, 100) daughter_size = (1300, 700) dad_hand_size = (400, 200) mom_hand_size = (1100,200) screenSize = (1100,1700) # 创建一个窗口 screen = pygame.display.set_mode(screenSize, 0, 32) # 设置窗口标题 pygame.display.set_caption('吃水果进程') # 加载图片并转换 # pygame.transform.scale(Surface, (width, height), DestSurface = None)(缩放) background = pygame.image.load(background_image_filename) background = pygame.transform.scale(background,(1100,1700)) appleim = pygame.image.load(apple_image_filename) appleim = pygame.transform.scale(appleim,(200,200)) orangeim = pygame.image.load(orange_image_filename) orangeim = pygame.transform.scale(orangeim,(200,200)) mom = pygame.image.load(mom_image_filename) mom = pygame.transform.scale(mom,(300,300)) father = pygame.image.load(father_image_filename) father = pygame.transform.scale(father,(300,300)) son = pygame.image.load(son_image_filename) son = pygame.transform.scale(son,(300,300)) daughter = pygame.image.load(daughter_image_filename) daughter = pygame.transform.scale(daughter,(300,300)) dad_hand = pygame.image.load(dad_hand_image_filename) dad_hand = pygame.transform.scale(dad_hand,(200,200)) mom_hand = pygame.image.load(mom_hand_image_filename) mom_hand = pygame.transform.scale(mom_hand,(200,200)) son_hand = pygame.image.load(son_hand_image_filename) son_hand = pygame.transform.scale(son_hand,(200,200)) daughter_hand = pygame.image.load(daughter_hand_image_filename) daughter_hand = pygame.transform.scale(daughter_hand,(200,200)) # 是否全屏 fullscreen = False mutex = threading.Lock() # 最大容量 capacity = 2 # 当前个数 num = 0 # 苹果个数 apple = 0 # 橘子个数 orange = 0 apple_lock = threading.Semaphore(0) orange_lock = threading.Semaphore(0) num_lock = threading.Semaphore(2) def daughter_eat(name): global num, capacity ,apple ,orange while True: apple_lock.acquire() num_lock.release() mutex.acquire() for i in range(5): screen.blit(background, (0, 0)) if num == 2: if orange == 2: blitOne(appleim) elif orange == 1: blitOne(orangeim) elif num == 1: pass blitPerson() screen.blit(daughter_hand, (1400 - i, 800 - i)) # 绘制的位置 pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() apple -= 1 num -= 1 print(name, "从桌子上拿走一个苹果") print("现在桌子上还有" + str(apple) + "苹果" + str(orange) + "橘子") mutex.release() time.sleep(3) def son_eat(name): global num, capacity, apple, orange while True: orange_lock.acquire() num_lock.release() mutex.acquire() for i in range(5): screen.blit(background, (0, 0)) if num == 2: if apple == 2: blitOne(orangeim) elif apple == 1: blitOne(appleim) elif num == 1: pass blitPerson() screen.blit(son_hand, (800 - i, 200 + i)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() orange -= 1 num -= 1 print(name, "从桌子上拿走一个橘子") print("现在桌子上还有" + str(apple) + "苹果" + str(orange) + "橘子") mutex.release() time.sleep(3) # 爸爸放苹果 def father_put(name, fruit): global num, capacity, apple, orange while True: num_lock.acquire() apple_lock.release() mutex.acquire() print(name, "把", fruit, "放在盘子里面") for i in range(5): screen.blit(background, (0, 0)) if i >= 4: if num == 0: blitOne(appleim) elif num == 1: if apple == 1: blitOne(appleim) blitTwo(appleim) else: blitOne(orangeim) blitTwo(appleim) blitPerson() screen.blit(dad_hand, (200 + i, 200 + i)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() apple += 1 num += 1 print("在爸爸放苹果之后,桌子上苹果的数量: " + str(apple) + " 桌子上橘子的数量: " + str(orange)) mutex.release() time.sleep(2) # 妈妈放的是橘子 def mother_put(name, fruit): global num, capacity, apple, orange while True: # 获取锁,用于线程同步 num_lock.acquire() # 释放锁 orange_lock.release() # 获取互斥变量的锁 mutex.acquire() print(name, "把", fruit, "放在盘子里面") for i in range(500): screen.blit(background, (0, 0)) if i >= 49: if num == 0: blitOne(orangeim) elif num == 1: if orange == 1: blitOne(orangeim) blitTwo(orangeim) else: blitOne(appleim) blitTwo(orangeim) blitPerson() screen.blit(mom_hand, (200 + i, 1100 - i)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() orange += 1 num += 1 print("在妈妈放橘子之后,桌子上苹果的数量: " + str(apple) + " 桌子上橘子的数量: " + str(orange)) mutex.release() time.sleep(2) def blitOne(fruit): screen.blit(fruit, one_size) blitPerson() def blitTwo(fruit): screen.blit(fruit, two_size) blitPerson() def blitPerson(): screen.blit(father, dad_size) screen.blit(mom, mom_size) screen.blit(son, son_size) screen.blit(daughter, daughter_size) if __name__ == "__main__": mother_thread = threading.Thread(target=mother_put, args=("妈妈", "橘子",)) father_thread = threading.Thread(target=father_put, args=("爸爸", "苹果",)) son_thread = threading.Thread(target=son_eat, args=("儿子",)) daughter_thread = threading.Thread(target=daughter_eat, args=("女儿",)) mother_thread.start() father_thread.start() son_thread.start() daughter_thread.start() time.sleep(10)
结果展示
问题及解决
1、 可视化页面设计之前,可以先绘制一个草图,并记录页面各点坐标。不要用PPT,不方便知道点之间的关系,可以用excel。
2、 Pygame可以加载图片pygame.image.load(image_filename)并调整大小pygame.transform.scale(background,(1100,1700))。
3、 设置线程变量锁apple_lock = threading.Semaphore(0),线程中如果需要使用变量,那么线程开始时上锁apple_lock.acquire(),线程结束时解锁mutex.release()。
4、 由于pygame会读取所有可视化页面上的操作,因此点击页面会卡死。可以加上一行关于事件点击的代码,解决这个问题
for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
5、 进程模块中,进程中不能改变gobal全局变量,可以用multiprocessing中的mp.value共享内存改变变量值。
6、 注意,定义一个共享内存l = mp.Lock()。共享内存操作前需要l.acquire() # 锁住,操作完成后需要l.release() # 释放。若进程作为def函数,那么共享内存锁需要作为参数一起被传过去。
7、 Multiprocessing模块中的 JoinableQueuea:
参考:https://blog.csdn.net/qq_36811322/article/details/88295637
其中,.get函数读取的是.put函数最后放到队列的那一个#(1, ‘苹果’)
实验心得
这个题是消费者—生产者问题的变形,需要先理清楚几点:
1、哪些操作是互斥的:对于盘子的访问要互斥的进行。且父母放与儿女拿需要两个不同的互斥量来实现,即m和n。
2、哪些操作是要同步进行的:父亲将苹果放入盘子后,女儿才能取苹果。母亲将橘子放入盘子后,儿子才能取橘子。只有盘子为空时,父亲或母亲才能放入水果,所以需要三个量来实现:put,orangeput,appleput。
3、对于互斥操作要一定是先P再V,将它夹在中间。对于同步操作,则是要使用的量,就P操作减一。对于可收回的量,就V操作加一。