LoginSignup
15
15

More than 5 years have passed since last update.

[python] pythonのキュー(queue)

Posted at

Pythonでは、キューとして
collections.deque(以下、 deque)と queue.Queue (以下、 Queue) がある。

両者の違い

deque

dequeDouble- Ended Queueの略称で、
名前通り、 両サイドからデータを入れたり取り出したりすることができるちょっと特殊なキューです。

図で表現しますと、

Kobito.edvWuD.png

上図は pythontic.comさんから借りてきた

  • 英語の表現がわかりやすいです

A deque is a double-ended queue on which elements can be added or removed from either side - that is on left end or right end, head or tail.

Queue

こちらは一般に認識されている FIFOキュー となります。

Kobito.b12TkZ.png

上図にあるように、片サイドからデータを入れたり、もう片サイドからデータを取り出したりすることになります。

queue.Queue と同じクラスに LifoQueuePriorityQueueも定義されいています。

queue.LifoQueue(maxsize=0)

LifoQueue は名前通り、queueのLIFO版です。
データ構造的には stackですね。

Kobito.QqVcNS.png

queue.PriorityQueue(maxsize=0)

queue.PriorityQueue は優先度付きキューです。
また今度説明します。

使い分け

  • マルチスレッド(複数プロデューサ-複数コンシューマ(multi-producer, multi-consumer))とかの場合は、スレッドセーフ設計(マルチスレッド対応)の queue.Queue を使用する。

  • シングルスレッドの場合は collections.deque を使用。理由は、スレッドセーフ設計のqueue.Queueより早いため。

15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15