python 线程条件变量锁

# _*_coding:utf-8_*_
# author:leo
# date:
# email:alplf123@163.com
import queue, threading


class Worker(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.lock = threading.Lock()
        self.con1 = threading.Condition(self.lock)
        self.con2 = threading.Condition(self.lock)
        self.event = threading.Event()# 也可以达到类似的效果,但是不够灵活,运用的场景不够丰富,此类也是线程安全
        self.queque = queue.Queue()
        print(self.event.is_set())
    
    def run(self):

        threading.Thread(target=self.customer).start()
        threading.Thread(target=self.producter).start()

    def producter(self):
        with self.con1:
            for a in range(100):
                print('productor put:', str(a))
                self.queque.put(a)
                self.con2.notify()
                self.con1.wait() #使用wait 必须保证当前是安全的 必须得到锁
                print('recevie sigal from con1 producting...')
            self.con2.notify_all()
    def customer(self):
        with self.con2:
            while True:

                self.con2.wait()
                print('recevie signal from con2 customer....')
                if self.queque.empty():
                    break
                result = self.queque.get()
                if result is not None:
                    print('customer get:', str(result))
                    self.con1.notify()

t = Worker()
t.start()
t.join()

 

转载于:https://www.cnblogs.com/alplf123/p/8542207.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值