python 多进程 事件(并行编程 14)

2019-07-30 11:08:24 浏览数 (1)

from multiprocessing import Event,Process import time import random

def tarffic_light(e): while True: while e.is_set(): print('33[1;32m绿灯亮33[0m') time.sleep(2) e.clear() else: print('33[1;31m红灯亮33[0m') time.sleep(2) e.set()

def car(i,e): while not e.is_set(): print(f'{i}正在等待通过...') e.wait() else: print(f'{i}通过.')

if name == 'main': e = Event() light = Process(target=tarffic_light,args=(e,)) light.daemon =True light.start() car_list = [] for i in range(1,21): p = Process(target=car,args=(i,e)) car_list.append(p) p.start() time.sleep(random.randint(0,3)) for i2 in car_list:i2.join() #控制子进程先执行完毕 print('执行完啦')

0 人点赞