from multiprocessing import Event,Process import time import random
def tarffic_light(e): while True: while e.is_set(): print('\033[1;32m绿灯亮\033[0m') time.sleep(2) e.clear() else: print('\033[1;31m红灯亮\033[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('执行完啦')