$ ls ~yifei/notes/

Python 中的 queue 模块

Posted on:

Last modified:

在 Python 中多进程或者多线程之间通信可以使用队列,标准库中实现了一个线程安全的库 queue.Queue,和进程安全的库 multiprocessing.Queue

q = Queue(size)

q.get(block=True)   # return a object
q.get_nowait()
q.put(item, block=True)   # put a object

q.qsize()
q.empty()
q.full()

q.task_done() # indicate one item process finished raise ValueError
q.join() # wait until all item processed

queue.Empty
queue.Full

尽管 queue.Queue 和 multiprocessing.Queue 的 API 几乎一致,但是实现是完全不同的。

如何遍历 queue?

sentinel = object()
for job in iter(queue.get, sentinel):
    ...

# when you would like to quit in other thread
queue.put(sentinel)

除了 FIFO queue 以外,Python 还提供了 LifoQueueHeapQueue

参考

  1. http://stackoverflow.com/questions/925100
  2. https://stackoverflow.com/a/21157892/1061155

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.