python生产者消费者简单模型

本文介绍了一个简单的生产者消费者模型实现,使用Python的threading模块创建多个生产者和消费者线程,通过队列来协调生产和消费的过程,展示了多线程环境下资源的共享与同步。

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

#!/usr/bin/python
import Queue
import time
import threading

q=Queue.Queue()

class producer(threading.Thread):
    def __init__(self,i):
        threading.Thread.__init__(self,name="producer Thread-%d" % i)
    def run(self):
        global q
        count=9
        while True:
            for i in range(3):
                if q.qsize() > 12:
                    pass
                else:
                    count=count+1
                    msg=str(count)
                    q.put(msg)
                    print self.name+' '+'producer'+msg+' '+'Queue Size:'+str(q.qsize())
                    
            time.sleep(2)

class consumer(threading.Thread):
    def __init__(self,i):
        threading.Thread.__init__(self,name="consumer Thread-%d" % i)
    def run(self):
        global q
        while True:
            for i in range(3):
                if q.qsize() < 1:
                    pass
                else:
                    msg=q.get()
                    print self.name+' '+'consumer'+msg+' '+'Queue Size:'+str(q.qsize())
            time.sleep(2)


def test():
    for i in range(10):
        q.put(str(i))
        print 'Init producer  '+str(i)
    for i in range(2):
        p=producer(i)
        p.start()
    for i in range(3):
        c=consumer(i)
        c.start()

if __name__ == '__main__':
    test()
生产者消费者模型
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值