開發與維運

隊列的使用

本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《Python入門2020最新大課》,主講人姜偉。

隊列的使用

import multiprocessing, queue

# q1 = multiprocessing.Queue()  # 進程間通信
# q2 = queue.Queue()  # 線程間通信


# 創建隊列時,可以指定最大長度。默認值是0,表示不限
q = multiprocessing.Queue(5)

q.put('hello')
q.put('good')
q.put('yes')
q.put('ok')
q.put('hi')

# print(q.full())  # True
# q.put('how')  # 無法放進去

# block = True:表示是阻塞,如果隊列已經滿了,就等待
# timeout 超時,等待多久以後程序會出錯,單位是秒
# q.put('how', block=True, timeout=5)

# q.put_nowait('how')  # 等價於  q.put('how',block=False)

print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
# print(q.get())
# q.get(block=True, timeout=10)
q.get_nowait()

配套視頻

Leave a Reply

Your email address will not be published. Required fields are marked *