码迷,mamicode.com
首页 > 编程语言 > 详细

【10.5】线程同步--conditon 使用以及源码分析

时间:2019-08-04 16:45:36      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:class   style   完成   env   thread   with   form   程序   __init__   

 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()收不到通知。
天猫 : 小爱同学
小爱 : 在
天猫 : 我们来对古诗吧
小爱 : 好啊

 

【10.5】线程同步--conditon 使用以及源码分析

标签:class   style   完成   env   thread   with   form   程序   __init__   

原文地址:https://www.cnblogs.com/zydeboke/p/11298632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!