2. Queue类,常用用于Greenlet之间的异步共享
q = gevent.queue.Queue(maxsize=None, items=None) -> Queue
说明: 创建一个指定大小包含指定items的队列对象
q.empty() -> Boolean
说明: 队列是否为空
q.full() -> Boolean
说明: 队列是否已满,如果初始化时maxsize为None时队列永远不会满,除非内存耗尽
q.get(block=True, timeout=None) -> obj
说明: 队列尾部弹出并返回末尾元素,block为True如果队列为空会一直等待,否则会抛出gevent.queue.Empty异常
q.get_nowait() -> obj
说明: 同q.get(block=False),如果队列为空直接返回gevent.queue.Empty
q.put(item, block=True, timeout=None) -> None
说明: 队列头部插入item,如果block为True则等待队列有空间时再插入,如果超出timeout则抛出Timeout异常,否则直接抛出gevent.queue.Full异常
q.put_nowait(self, item) -> None
说明: 同q.put(block=False),如果队列满直接返回gevent.queue.Full
q.qsize() -> int
说明: 返回队列的元素数
import gevent from gevent.queue import Queue # 队列是一个排序的数据集合 put和get都有非阻塞模式,put_nowait和get_nowait不会阻塞,在操作不能完成时抛出gevent.queue.Empty或gevent.queue.Full异常 tasks = Queue() def worker(n): while not tasks.empty(): task = tasks.get() print('worker %s got task %s'%(n, task)) gevent.sleep(0) print('Quitting time!') def boss(): for i in xrange(1, 25): tasks.put_nowait(i) gevent.spawn(boss).join() gevent.joinall([ gevent.spawn(worker, 'steve'), gevent.spawn(worker, 'john'), gevent.spawn(worker, 'nancy'), ])
# coding:utf-8 import gevent from gevent.queue import Queue, Empty, LifoQueue, PriorityQueue # 先进先出 # 先进后出 # 优先级队列 class Job(): def __init__(self, prority, des): self.prority = prority self.des = des def __cmp__(self, other): return cmp(self.prority, other.prority) def __str__(self): return 'prority %d des %s'%(self.prority, self.des) q = LifoQueue() q.put(Job(3, 'mid job')) q.put(Job(10, 'low job')) q.put(Job(1, 'important job')) while not q.empty(): job = q.get() print(job)
joinableQueue JoinableQueue 比Queue多了task_done() 与join()两个函数,都是专用于全球进行编程的,当然多是生产者消费者问题。 task_done() 是用在get()后,告诉os, 我get完了,join()是说Queue里所有的items都被拿出来搞完了。 --------------------- 参考来自 heavendai 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/heavendai/article/details/24380325?utm_source=copy
# coding:utf-8 import gevent from gevent import Greenlet from gevent.queue import JoinableQueue, Empty # 主队列 class Actor(Greenlet): def __init__(self, data): self.data = data Greenlet.__init__(self) def _run(self): result = do_something(self.data) return result def do_something(data): print('the data is %s'%data) queue = JoinableQueue() def boss(): for i in xrange(1, 1000): queue.put_nowait(i) boss() def work(): while True: try: data = queue.get(timeout=5) print('data is %s'%data) except Empty: gevent.sleep(0.5) break finally: queue.task_done() # queue.join() # 交付给Actor # if data: # g1 = Actor(data) # g1.start() # g1.join() for i in range(5): gevent.spawn(work) queue.join()