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之后才能启动

0
2
bobby
回复
宗介呀
执行notify之后的逻辑是否会执行 其实最好的验证方法就是自己写代码测试一下
2021-02-22
共2条回复

宗介呀

提问者

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()

0
0

bobby

2021-02-20

你发一下完整的代码 我看看

0
1
宗介呀
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()
2021-02-20
共1条回复

Python3高级核心技术97讲,高级进阶的必学课程

socket编程/多线程/多进程/线程池/asyncio并发编程/协程和异步IO

2121 学习 · 551 问题

查看课程