python 线程之 threading(四)

python 线程之 threading(三) http://www.cnblogs.com/someoneHan/p/6213100.html中对Event做了简单的介绍。

但是如果线程打算一遍一遍的重复通知某个事件。应该使用Condition

1. 使用Condition首先应该获取Condition即使Condition进入锁的状态

2. 在线程执行过程中需要等待其他线程通知,然后才开始向下运行的地方使用Condition.wait()方法,线程进入阻塞状态。

3. 使用Condition对锁进行release().

4. 如果Condition通知所有的等待线程继续运行可以使用notify_all()方法,如果只是唤醒其中的一个线程使用notify方法

 1 import threading
 2 import time
 3 
 4 
 5 class CountDown(threading.Thread):
 6     def __init__(self, startNum, condition):
 7         self.condition = condition
 8         self.startNum = startNum
 9         threading.Thread.__init__(self)
10 
11     def run(self):
12         while self.startNum > 0:
13             with self.condition:
14                 self.startNum -= 1
15                 print('countdown current num :', self.startNum)
16                 self.condition.wait()
17 
18 
19 class CountUp(threading.Thread):
20     def __init__(self, startNum, condition):
21         self.condition = condition
22         self.startNum = startNum
23         threading.Thread.__init__(self)
24 
25     def run(self):
26         while self.startNum < 100:
27             with self.condition:
28                 self.startNum += 1
29                 print('countup current num:', self.startNum)
30                 self.condition.wait()
31 
32 condition = threading.Condition()
33 countdown = CountDown(100, condition)
34 countdown.start()
35 countup = CountUp(0, condition)
36 countup.start()
37 for i in range(100):
38     with condition:
39         print('notify')
40         condition.notify_all()#如果只通知一个线程继续运行使用 condition.notify()
41     time.sleep(1)

 

posted @ 2016-12-23 23:21  someOneHan  阅读(195)  评论(0编辑  收藏  举报