Python3-queue模塊-同步隊列

Python3中的queue模塊實現多生產者,多消費者隊列,特別適用於多個線程間的信息的安全交換,主要有三個類html

  queue.Queue(maxsize=0)python

    構造一個FIFO(先進先出)的隊列安全

  queue.LifoQueue(maxsize=0)ide

    構造一個LIFO(後進先出)的隊列spa

  queue.PriorityQueue(maxsize=0)線程

    構造一個具備優先級的隊列,存儲的是一個元組(n, value),n爲數字表明優先級,數字越小,級別越高code

這個模塊定義了兩個異常htm

  queue.Emptyblog

    若是隊列中爲空,繼續調用非阻塞的get_nowait()會拋出異常three

  queue.Full

    若是隊列已滿,繼續調用非阻塞的put_nowait()會拋出異常

import queue
# 如下三個隊列均可以設置最大長度maxsize,默認是無限大
print("-------------queue.Queue----------------")
# 線程消息隊列,FIFO(先進先出)
q = queue.Queue()
q.put("one")
q.put("two")
q.put("three")
print(q.get())
print(q.get())
print(q.get())
# print(q.get(timeout=3))     # 隊列中沒有數據,會阻塞

print("-------------queue.LifoQueue----------------")
# 線程消息隊列,LIFO(後進先出)
lq = queue.LifoQueue()
lq.put("one")
lq.put("two")
lq.put("three")
print(lq.get())
print(lq.get())
print(lq.get())

print("-------------queue.PriorityQueue----------------")
# 線程消息隊列,PriorityQueue(優先級的隊列:數字越小優先級越高)
pq = queue.PriorityQueue()
pq.put((1, "Jet"))
pq.put((3, "Jack"))
pq.put((2, "Judy"))
print(pq.get())
print(pq.get())
print(pq.get())
View Code

參考資料

  http://python.usyiyi.cn/translate/python_352/library/queue.html

相關文章
相關標籤/搜索