条件同步和条件变量同步差不多意思,只是少了锁功能,因为条件同步设计于不访问共享资源的条件环境,event=threading.Event():条件环境对象,初始值为False.
event.isSet(): 返回event的状态值
event.wait(): 如果event.isSet()==False将阻塞线程
event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态,等待操作系统调度
event.clear(): 恢复event的状态值为False
1 import time,threading 2 3 class Boss(threading.Thread): 4 def run(self): 5 print('Boss:今晚加班到22:00') 6 event.isSet()or event.set() 7 time.sleep(5) 8 print('Boss:<22:00>可以下班了') 9 event.isSet()orevent.set() 10 11 class Worker(threading.Thread): 12 def run(self): 13 event.wait() 14 print('Worker:命苦啊~') 15 time.sleep(0.25) 16 event.clear() 17 event.wait() 18 print('Worker:oh,yeah') 19 20 if __name__ == '__main__': 21 event = threading.Event() 22 threads = [] 23 for i in range(5): 24 threads.append(Worker()) 25 threads.append(Boss()) 26 for t in threads: 27 t.start() 28 for t in threads: 29 t.join()
1 import threading,time 2 import random 3 def light(): 4 if not event.isSet(): 5 event.set() #wait就不阻塞 #绿灯状态 6 count = 0 7 while True: 8 if count < 10: 9 print('