本程序参考链接https://www.cnblogs.com/chengd/articles/7770898.html
Python threading模块提供Event对象用于线程间通信。用于主线程控制其他线程的执行,事件主要提供了四个方法wait、clear、set、isSet
- set():可设置Event对象内部的信号标志为True
- clear():可清除Event对象内部的信号标志为False
- isSet():Event对象提供了isSet()方法来判断内部的信号标志的状态。当使用set()后,isSet()方法返回True;当使用clear()后,isSet()方法返回False
- wait():该方法只有在内部信号为True的时候才会被执行并完成返回。当内部信号标志为False时,则wait()一直等待到其为True时才返回
通过Event来实现一个红绿灯例子,
即启动一个线程做交通指挥灯,生成几个线程做汽车,汽车行驶按照红灯停绿灯行的规则
1 #cherry_cui 2 3 4 import threading, time #导入所需的模块 5 import random 6 7 def light(): #定义light函数 8 if not event.isSet(): 9 event.set() 10 # 初始化isSet()为True:若isSet为True,不执行set();若isSet为False,执行set() 11 count = 0 12 while True: 13 if count < 10: 14 print('\033[42;1m---green light on---\033[0m') 15 elif count < 13: 16 print('\033[43;1m---yellow light on---\033[0m') 17 elif count < 20: 18 if event.isSet(): #若isSet()为True,执行clear(),isSet()返回False 19 event.clear() 20 print('\033[41;1m---red light on---\033[0m') 21 else: 22 count = 0 23 event.set() #打开绿灯 24 time.sleep(1) #休眠1s才能让car()有机会获取CPU的执行权 25 count += 1 26 27 def car(n): #定义car函数 28 while 1: 29 time.sleep(random.randrange(3, 10)) #休眠3s到10s(随机)才能让light()有机会获取CPU的执行权 30 print(event.isSet()) #打印当前light()中isSet的状态 31 if event.isSet(): #获取light()中isSet的状态,若为True则执行下一个语句 32 print("car [%s] is running..." % n) 33 else: 34 print('car [%s] is waiting for the red light...' % n) 35 #event.wait() #红灯状态下调用wait方法阻塞,汽车等待状态 36 37 if __name__ == '__main__': 38 car_list = ['aa', 'bb', 'cc'] #定义car数组 39 event = threading.Event() 40 #通过threading.Event()生成一个event对象和对象的引用event 41 42 Light = threading.Thread(target=light) 43 #创建一个以light为目标的线程任务 44 Light.start() #启动Light线程 45 46 for i in car_list: #遍历car数组 47 t = threading.Thread(target=car, args=(i,)) 48 # 创建一个以car方法的线程任务,传car数组的数据给car() 49 t.start() #启动t线程
运行结果: