1 #!/user/bin/env python
2 # -*- coding:utf-8 -*-
3
4 # 条件变量,用于复杂的线程间同步
5 # 通过condition完成协同读诗
6 from threading import Lock
7 from threading import Condition
8 import threading
9
10
11 class XiaoAi(threading.Thread):
12 def __init__(self, cond):
13 super().__init__(name='小爱')
14 self.cond = cond
15
16 def run(self):
17 with self.cond:
18 # 等待
19 self.cond.wait()
20 print('{} : 在'.format(self.name))
21 # 通知
22 self.cond.notify()
23 # 等待
24 self.cond.wait()
25 print('{} : 好啊'.format(self.name))
26 # 通知
27 self.cond.notify()
28
29
30 class TianMao(threading.Thread):
31 def __init__(self, cond):
32 super().__init__(name='天猫')
33 self.cond = cond
34
35 def run(self):
36 # 建议使用with语句,不然acquire和release一定要成对出现
37 with self.cond:
38 print('{} : 小爱同学'.format(self.name))
39 # 通知
40 self.cond.notify()
41 # 等待
42 self.cond.wait()
43 print('{} : 我们来对古诗吧'.format(self.name))
44 # 通知
45 self.cond.notify()
46 # 等待
47 self.cond.wait()
48
49
50 if __name__ == '__main__':
51 cond = threading.Condition()
52 xiao_ai = XiaoAi(cond)
53 tian_mao = TianMao(cond)
54
55 # 启动的先后顺序很重要
56 # 在调用with方法,或者acquire方法之后,再调用wait和notify方法
57 xiao_ai.start()
58 tian_mao.start()
59
60 # 先启动tian_mao,会打印出‘小爱同学’,但程序会‘死掉’,这是因为self.cond.notify()通知已经发出去了
61 # 但是后面启动xiao_ai,xiao_ai的self.cond.wait()收不到通知。
天猫 : 小爱同学
小爱 : 在
天猫 : 我们来对古诗吧
小爱 : 好啊