首页 > 编程语言 > 详细

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

时间:2019-02-12 11:30:13      阅读:216      评论:0      收藏:0      [点我收藏+]

 

#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!"

 

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

原文:https://www.cnblogs.com/sea-stream/p/10364280.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!