python (协程)生产者,消费者

本文介绍了一种使用Python的gevent库实现的任务队列系统。通过限制队列大小和利用协程,实现了任务的高效分发和处理。演示了如何在多个工作线程间分配任务,并展示了在所有任务完成后的工作线程退出机制。

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

 

#coding=utf-8
import gevent
from gevent.queue import Queue, Empty
import time
tasks = Queue(maxsize=4)
 
def worker(n):
    try:
        while True:
            task = tasks.get(timeout=1) # decrements queue size by 1
            print('Worker %s got task %s' % (n, task))
            gevent.sleep(1)
    except Empty:
        print('Worker %s says:\"Quitting time!\"' % (n))
 
def boss():
    """
    Boss will wait to hand out work until a individual worker is
    free since the maxsize of the task queue is 3.
    """
 
    for i in range(1,10):
        tasks.put(i)
    print('Assigned all work in iteration 1')#添加完毕
 
    for i in range(10,20):
        tasks.put(i)
    print('Assigned all work in iteration 2')#添加完毕
t1=time.time()
gevent.joinall([
    gevent.spawn(boss),
    gevent.spawn(worker, 'steve'),
    gevent.spawn(worker, 'john'),
    gevent.spawn(worker, 'bob'),
])
print(time.time()-t1)

输出

Worker steve got task 1
Worker john got task 2
Worker bob got task 3
Worker steve got task 4
Worker john got task 5
Worker bob got task 6
Assigned all work in iteration 1
Worker steve got task 7
Worker john got task 8
Worker bob got task 9
Worker steve got task 10
Worker john got task 11
Worker bob got task 12
Worker steve got task 13
Worker john got task 14
Worker bob got task 15
Assigned all work in iteration 2
Worker steve got task 16
Worker john got task 17
Worker bob got task 18
Worker steve got task 19
Worker john says:"Quitting time!"
Worker bob says:"Quitting time!"
Worker steve says:"Quitting time!"

 

转载于:https://www.cnblogs.com/sea-stream/p/10364280.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值