首页 > 其他 > 详细

★ Contidion wait+notify方法

时间:2020-07-02 10:18:24      阅读:66      评论:0      收藏:0      [点我收藏+]
  在调用 with cond 之后才能调用wait和notify方法
在condition 里面有两层锁,一把锁会在线程调用wait方法的时候释放,上面的锁会在每次调用wait的时候分配一把并
放入cond中的等待队列中,知道notify方法唤醒


技术分享图片



此处唤醒的进程时随机!!!

技术分享图片

 

聊天尝试对两个进程互相切换的实现

 

 1 import threading
 2 
 3 from threading import Condition
 4 
 5 class ZhangSan(threading.Thread):
 6     def __init__(self,cond):
 7         super().__init__(name=张三)
 8         self.cond=cond
 9 
10     def run(self):
11         with self.cond:
12             print("{}:你好".format(self.name))        #1
13             self.cond.notify()
14             self.cond.wait()
15 
16             print("{}:lalala".format(self.name))
17             self.cond.notify()
18             self.cond.wait()
19 
20 
21 class LiSi(threading.Thread):
22     def __init__(self,cond):
23         super().__init__(name=李四)
24         self.cond = cond
25     def run(self):
26         with self.cond:
27             self.cond.wait()            #关键
28             print("{}:你好".format(self.name))
29             self.cond.notify()
30 
31             self.cond.wait()
32             print("{}:滚犊子".format(self.name))
33             self.cond.notify()
34             # print("{}:滚犊子".format(self.name))
35 
36 
37 if __name__ == __main__:
38     cond = threading.Condition()
39     zhangsan = ZhangSan(cond)
40     lisi = LiSi(cond)
41 
42     #   程序的执行顺序
43     lisi.start()
44     zhangsan.start()

 

★ Contidion wait+notify方法

原文:https://www.cnblogs.com/sdosun/p/13222417.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!