隊列的簡單使用,隊列先進先出
import queue # 不能用於多進程之間的通訊,可以用於多線程間的通訊 from multiprocessing import Queue # 可以用於進程之間的數據共享 q = Queue(3) # 創建一個隊列對象,隊列長度為3 q.put(1) q.put(2) q.put(3) # q.put(4) # 當隊列已滿,繼續放值,,會阻塞程序 try: q.put_nowait(4) # 等同於 q.put(4, False) except: print("隊列已經滿了.") print(q.get()) print(q.get()) print(q.get()) # print(q.get()) # 當隊列空了,繼續取值,也會阻塞程序 try: q.get_nowait() # 等同於q.get(block=False) except: print("隊列已經空了.")
執行結果:
隊列已經滿了. 1 2 3 隊列已經空了.
隊列的使用
from multiprocessing import Queue q = Queue(5) q.put("one") q.put("two") q.put("three") q.put("four") q.put("five") # q.put("six") # 隊列的長度只有5,此時程序會阻塞在這里 print(q.get()) print(q.get()) print(q.get()) print(q.get()) print(q.get()) # print(q.get()) # 此時隊列是空的,從空隊列中拿數據也會阻塞
執行結果:
one
two
three
four
five