python 线程条件变量锁

Posted 我是外婆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 线程条件变量锁相关的知识,希望对你有一定的参考价值。

# _*_coding:utf-8_*_
# author:leo
# date:
# email:[email protected]
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()

 

以上是关于python 线程条件变量锁的主要内容,如果未能解决你的问题,请参考以下文章

python线程的条件变量Condition的用法实例

Python 线程条件变量 Condition

python笔记11-多线程之Condition(条件变量)

python笔记11-多线程之Condition(条件变量)

线程同步

python多线程编程5: 条件变量同步-乾颐堂