wait和notify的疑惑
来源:11-5 线程同步 - condition 使用以及源码分析

宗介呀
2021-02-19
老师您好,
notify方法的源码中直接释放锁,执行完notify方法后,不是应该直接执行xiaoai的代码段了吗?为何tianmao的wait方法执行后才会执行xiaoai的代码段呢?
print(“小爱同学”)
self.cond.notify()
self.cond.wait()
3回答
-
bobby
2021-02-21
你可以这样理解, condition只有的wait只有通过condition的notify才能唤醒,所以xiaoai只有通过天猫的notify之后才能启动
022021-02-22 -
宗介呀
提问者
2021-02-20
import threading
from threading import Condition
class XiaoAi(threading.Thread):
def __init__(self, cond):
super().__init__(name="小爱")
self.cond = cond
def run(self):
with self.cond:
self.cond.wait()
print("在呢")
self.cond.notify()
self.cond.wait()
print("好的")
self.cond.notify()
self.cond.wait()
print("近看还是一头猪")
self.cond.notify()
class TianMao(threading.Thread):
def __init__(self, cond):
super().__init__(name="天猫精灵")
self.cond = cond
def run(self):
with self.cond:
print("小爱同学")
self.cond.notify()
self.cond.wait()
print("我们来对古诗吧")
self.cond.notify()
self.cond.wait()
print("远看一头猪")
self.cond.notify()
self.cond.wait()
if __name__ == '__main__':
# condition有两层锁,一把地层锁,会在线程调用了wait的时候进行释放,上面的锁,会在每次调用wait的时候分配一把,并放到condition的等待队列中,等待notify方法的唤醒
cond = Condition()
xiao_ai = XiaoAi(cond)
tian_mao = TianMao(cond)
xiao_ai.start()
tian_mao.start()00 -
bobby
2021-02-20
你发一下完整的代码 我看看
012021-02-20
相似问题