#coding=utf-
import gevent
from gevent.queue import Queue, Empty
import time
tasks = Queue(maxsize=) def worker(n):
try:
while True:
task = tasks.get(timeout=) # decrements queue size by
print('Worker %s got task %s' % (n, task))
gevent.sleep()
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 .
""" for i in range(,):
tasks.put(i)
print('Assigned all work in iteration 1')#添加完毕 for i in range(,):
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
Worker john got task
Worker bob got task
Worker steve got task
Worker john got task
Worker bob got task
Assigned all work in iteration
Worker steve got task
Worker john got task
Worker bob got task
Worker steve got task
Worker john got task
Worker bob got task
Worker steve got task
Worker john got task
Worker bob got task
Assigned all work in iteration
Worker steve got task
Worker john got task
Worker bob got task
Worker steve got task
Worker john says:"Quitting time!"
Worker bob says:"Quitting time!"
Worker steve says:"Quitting time!"