python中多线程消费者生产者问题

本文介绍了一种使用Python的threading模块实现的多线程生产者消费者模式。通过面向对象的方式,创建了Producer和Consumer两个类,分别用于生产数据和消费数据。数据通过一个队列进行传递,实现了生产者和消费者的解耦。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

threading的消费,生产实现

# 面向对象的消费者和生产者模式.
"""
多线程.
"""
from threading import Thread
import queue
import random
import time


class Producer(Thread):
    def __init__(self, queue):  # 重写.
        super().__init__()  # 加入父类init.
        self.queue = queue

    def run(self):  # call start()时 就会调用run(run为单线程).
        while True:
            item = random.randint(0, 99)  # left is closed and right is closed.
            self.queue.put(item)
            print("Producer-->%s" % item)
            time.sleep(1)


class Consumer(Thread):
    def __init__(self, queue):  # 重写.
        super().__init__()  # 加入父类init.
        self.queue = queue

    def run(self):  # call start()时 就会调用run(run为单线程).
        while True:
            item = self.queue.get()
            print("Consumer-->%s" % item)
            self.queue.task_done()


# main + tab
if __name__ == '__main__':
    q1 = queue.Queue()

    p = Producer(q1)
    c = Consumer(q1)
    p.start()
    c.start()
    p.join()
    c.join()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值