美文网首页
多线程:生产者消费者模型

多线程:生产者消费者模型

作者: 陈忠俊 | 来源:发表于2020-08-08 21:47 被阅读0次
from threading import Thread, Condition
from queue import Queue
import random
import time

condition = Condition()
products = Queue(5)

class Producer(Thread):
    def __init__(self, thread_id):
        super().__init__()
        self.thread_id = thread_id

    def run(self):
        while True:
            if condition.acquire():
                if not products.full(): # 如果队列不是满,生产数据
                    products.put(random.randint(1, 100))
                    print("Call consumer now, we have products")
                    condition.notify() # 通知消费者消费
                else: #如果队列是满的,通知消费者,并停止生产
                    condition.notify()
                    condition.wait()
                condition.release()
                time.sleep(0.1)

class Consumer(Thread):
    def __init__(self, thread_id):
        super().__init__()
        self.thread_id = thread_id

    def run(self):
        while True:
            if condition.acquire():
                if not products.empty(): # 如果队列不为空,则消费数据
                    print("consumer get a product now: %d" %products.get())
                else: # 如果产品队列是空的,通知生产者开始生产,并停止消费
                    print("No products now, wait...")
                    condition.notify()
                    condition.wait()
                condition.release()
                time.sleep(0.1)

p = Producer('producer')
c = Consumer('consumer')

p.start()
c.start()

相关文章

网友评论

      本文标题:多线程:生产者消费者模型

      本文链接:https://www.haomeiwen.com/subject/ypkkdktx.html