python多线程之Condition(条件变量)

Posted

tags:

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-


from threading import Thread, Condition
import time

items = []
condition = Condition()

class Consumer(Thread):
    def __init__(self):
        Thread.__init__(self)

    def consume(self):
        global condition
        global items

        condition.acquire()
        if len(items) == 0:
            condition.wait()
            print ("Consumer notify: no item to consume")
        items.pop()
        print("Consumer notify: consumed 1 item")
        print("Consumer nofity: items to consume are "              + str(len(items)))
        condition.notify()
        condition.release()

    def run(self):
        for i in range(0, 20):
            time.sleep(4)
            self.consume()

class Producer(Thread):
    def __init__(self):
        Thread.__init__(self)

    def produce(self):
        global condition
        global items

        condition.acquire()
        if len(items) == 10:
            condition.wait()
            print ("Producer notify: item producted are"                   + str(len(items)))
            print("Producer nofity: stop the production!!")
        items.append(1)
        print("Producer nofity: total items producted "              + str(len(items)))
        condition.notify()
        condition.release()

    def run(self):
        for i in range(0, 20):
            time.sleep(1)
            self.produce()


if __name__ == "__main__":
    producer = Producer()
    consumer = Consumer()
    producer.start()
    consumer.start()
    producer.join()
    consumer.join()
    
        

技术分享

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

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

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

Python 线程条件变量 Condition

python高级之多线程

[多线程]C++11多线程-条件变量(std::condition_variable)

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