Python中协程Event()函数

python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法wait、clear、set

事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么执行event.wait 方法时便不再阻塞。

  • clear:将“Flag”设置为False
  • set:将“Flag”设置为True

用 threading.Event 实现线程间通信,使用threading.Event可以使一个线程等待其他线程的通知,我们把这个Event传递到线程对象中,

Event默认内置了一个标志,初始值为False。一旦该线程通过wait()方法进入等待状态,直到另一个线程调用该Event的set()方法将内置标志设置为True时,该Event会通知所有等待状态的线程恢复运行。

 1 #!/usr/bin/python3
 2 #_*_ coding: UTF-8 _*_
 3 
 4 
 5 import threading, time
 6 import random
 7 
 8 def light():
 9     if not event.isSet():
10         event.set()  #wait就不阻塞 #绿灯状态
11     count = 0
12     i=0
13     while True:
14         if count <10:
15             print("---green light on ---")
16         elif count<13:
17             print("---yellow light on ---")
18         elif count <20:
19             if event.isSet():
20                 event.clear()
21             print("---red light on ---")
22         else:
23             count = 0
24             event.set()#打开绿灯
25         time.sleep(1)
26         count +=1
27         i+=1
28         if(i>20):
29             break
30 def car(n):
31     i=0
32     while 1:
33         time.sleep(random.randrange(3))
34         if event.isSet():#如果是绿灯
35             print("car [%s] is running.."%n)
36         else:
37             print("car [%s] is waiting for the red light.."%n)
38         if(i>10):
39             break
40         else:
41             i+=1
42         
43 if __name__ == '__main__':
44     event = threading.Event()
45     Light = threading.Thread(target=light)
46     Light.start()
47     for i in range(3):
48         t = threading.Thread(target=car,args=(i,))
49         t.start()
50     
原文地址:https://www.cnblogs.com/hoojjack/p/6639128.html