MULTITHREADING - PRODUCER AND CONSUMER WITH QUEUE

本文通过Python的Queue模块实现了一个生产者消费者模型。在这个模型中,生产者线程不断地生成随机数并放入队列,而消费者线程则不断地从队列中取出这些数值。该模型展示了如何有效地在多线程环境中同步数据。

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

Queue

In this chapter, we'll implement another version of Producer and Consumer code with Queue(see Condition objects with producer and consumer).

In the following example, the Consumer and Producer threads runs indefinitely while checking the status of the queue. The Producer thread is responsible for putting items into the queue if it is not full while the Consumer thread consumes items if there are any.

import threading
import time
import logging
import random
import Queue

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-9s) %(message)s',)

BUF_SIZE = 10
q = Queue.Queue(BUF_SIZE)

class ProducerThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        super(ProducerThread,self).__init__()
        self.target = target
        self.name = name

    def run(self):
        while True:
            if not q.full():
                item = random.randint(1,10)
                q.put(item)
                logging.debug('Putting ' + str(item)  
                              + ' : ' + str(q.qsize()) + ' items in queue')
                time.sleep(random.random())
        return

class ConsumerThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        super(ConsumerThread,self).__init__()
        self.target = target
        self.name = name
        return

    def run(self):
        while True:
            if not q.empty():
                item = q.get()
                logging.debug('Getting ' + str(item) 
                              + ' : ' + str(q.qsize()) + ' items in queue')
                time.sleep(random.random())
        return

if __name__ == '__main__':
    
    p = ProducerThread(name='producer')
    c = ConsumerThread(name='consumer')

    p.start()
    time.sleep(2)
    c.start()
    time.sleep(2)
Output:(producer ) Putting 2 : 1 items in queue(producer ) Putting 10 : 2 items in queue(producer ) Putting 6 : 3 items in queue(producer ) Putting 7 : 4 items in queue(producer ) Putting 1 : 5 items in queue(consumer ) Getting 2 : 4 items in queue(consumer ) Getting 10 : 3 items in queue(producer ) Putting 1 : 4 items in queue(producer ) Putting 8 : 5 items in queue(consumer ) Getting 6 : 4 items in queue(producer ) Putting 10 : 5 items in queue...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值