二十九、Python threading.Event 和 condition

Event

Event是 线程间通信间的机制之一:一个线程发送一个event信号,其他的线程则等待这个信号。用于主线程控制其他线程的执行。Events 管理一个flag,这个flag可以使用se()设置成True或者使用clear() 重置为False, wait() 则用于阻塞,在flag 为True 之前。flag 默认为False。

 

  • Event.wait() : 阻塞,直到Event 对象内部标识位flag被设置为true 或者超时。
  • Event.set() :  将标识位设置为True
  • Event.clear(): 清除标识位False
  • Event.isSet(): 判断标识位是否为True

当线程执行的时候,如果flag 为False,则线程会阻塞。当flag为True 的时候,线程不会阻塞。它提供了本地和远程的并发性。

 

 1 import threading
 2 
 3 
 4 def do(event):  #传递的一个参数是一个event对象
 5     print('start')
 6     event.wait()
 7     print('execute')
 8 
 9 event_obj = threading.Event()  #创建event 对象
10 
11 for i in range(3):
12     t = threading.Thread(target = do, args = (event_obj,)) #创建线程
13     t.start()  #启动后执行run,执行do 中的语句,会执行到wart方法
14 
15 
16 event_obj.clear() #将标识设置为Flase
17 
18 inp = input('input:')
19 
20 if inp == 'true':  
21     event_obj.set()  #将标识设置为True, 不在阻塞,继续执行

 

Condition

condition 与某类型的锁类似。 condition 服从上下文管理协议,with语句块封闭Ian,可以获取与锁的联系

acruire() release()会调用与锁相关联的方法。

 

其他和锁关联的方法必须被调用,wait()方法会释放锁,当另外一个线程使用notify() or notify_all() 唤醒它前会一直阻塞。一旦被唤醒,wait()会重新获得锁并返回。

 

Condition 类实现了一个condition变量。这个condition变量允许一个或者多个线程等待,直到他们被另外一个线程通知。

wait(timeout=None): 等待通知。

nofity() 方法会唤醒一个在等待condition变量的线程。notify_all()则会唤醒所有在等待condition变量的线程

 1 import threading
 2 import time
 3 def consumer(cond):
 4     with cond:
 5         print('consumer before wait')
 6         cond.wait()
 7         print('consumer after wait')
 8 
 9 def producer(cond):
10     with cond:
11         print('producer before notifyall')
12         cond.notifyAll()
13         print('producer after notifyall')
14 
15 
16 condition = threading.Condition()
17 
18 c1 = threading.Thread(name='c1',target=consumer,args=(condition,))
19 c2 = threading.Thread(name='c2',target=consumer,args=(condition,))
20 
21 p = threading.Thread(name='p',target=producer,args=(condition,))
22 
23 c1.start()
24 time.sleep(3)
25 
26 c2.start()
27 time.sleep(3)
28 
29 p.start()
30 
31 
32 
33 C:\Python35\python.exe D:/Python0618/homework/day10/a.py
34 consumer before wait
35 consumer before wait
36 producer before notifyall
37 producer after notifyall
38 consumer after wait
39 consumer after wait

 

posted @ 2016-07-26 19:40  咖啡茶  阅读(845)  评论(0)    收藏  举报