040同步条件event

2018-06-18 01:48:54来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 

条件同步和条件变量同步差不多意思,只是少了锁功能,因为条件同步设计于不访问共享资源的条件环境,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()
View Code
 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('\033[42;1m--green light on---\033[0m')
10         elif count <13:
11             print('\033[43;1m--yellow light on---\033[0m')
12         elif count <20:
13             if event.isSet():
14                 event.clear()
15             print('\033[41;1m--red light on---\033[0m')
16         else:
17             count = 0
18             event.set() #打开绿灯
19         time.sleep(1)
20         count +=1
21 def car(n):
22     while 1:
23         time.sleep(random.randrange(10))
24         if  event.isSet(): #绿灯
25             print("car [%s] is running.." % n)
26         else:
27             print("car [%s] is waiting for the red light.." %n)
28 if __name__ == '__main__':
29     event = threading.Event()
30     Light = threading.Thread(target=light)
31     Light.start()
32     for i in range(3):
33         t = threading.Thread(target=car,args=(i,))
34         t.start()
View Code

 

来自:http://www.cnblogs.com/yuanchenqi/articles/5733873.html

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python 学习笔记(六)Python第一个程序

下一篇:Python 学习笔记(七)Python字符串(一)