多线程中的条件变量condition

# coding: utf-8
from threading import Condition
import threading
# 条件变量, 用于复杂的线程间同步


class XiaoAi(threading.Thread):
    def __init__(self, cond):
        super().__init__(name='小爱同学')
        self.cond = cond

    def run(self):
        # 条件变量
        with self.cond:
            # 等候变量释放
            self.cond.wait()
            print('{} : 在'.format(self.name))
            # 发送释放变量信号
            self.cond.notify()

            self.cond.wait()
            print('{} : 好啊!'.format(self.name))
            self.cond.notify()

            self.cond.wait()
            print('{} : 君住长江尾'.format(self.name))
            self.cond.notify()

            self.cond.wait()
            print('{} : 共饮长江水'.format(self.name))
            self.cond.notify()

            self.cond.wait()
            print('{} : 此恨何时已'.format(self.name))
            self.cond.notify()

            self.cond.wait()
            print('{} : 定不负相思意'.format(self.name))
            self.cond.notify()


class TianMao(threading.Thread):
    def __init__(self, cond):
        super().__init__(name='天猫精灵')
        self.cond = cond

    def run(self):
        # 条件变量
        with self.cond:
            print('{} : 小爱同学'.format(self.name))
            self.cond.notify()
            self.cond.wait()

            print('{} : 我们来对古诗吧!'.format(self.name))
            self.cond.notify()
            self.cond.wait()

            print('{} : 我住长江头'.format(self.name))
            self.cond.notify()
            self.cond.wait()

            print('{} : 日日思君不见君'.format(self.name))
            self.cond.notify()
            self.cond.wait()

            print('{} : 此水几时休'.format(self.name))
            self.cond.notify()
            self.cond.wait()

            print('{} : 只愿君心似我'.format(self.name))
            self.cond.notify()
            self.cond.wait()


if __name__ == '__main__':
    cond = Condition()
    xiaoai = XiaoAi(cond)
    tianmao = TianMao(cond)
    # 启动顺序很重要
    # 在调用with 之后才能调用notify或wait
    # condition 有两层锁, 一把底层锁会在线程调用了wait方法的时候释放上面的锁会在每次调用wait的时候分配一把放入到cond的等待队列中 等待notify方法的唤醒
    xiaoai.start()
    tianmao.start()


猜你喜欢

转载自blog.csdn.net/weixin_34191845/article/details/91000554