1. 程式人生 > >佇列get函式和get_nowait函式及異常捕獲

佇列get函式和get_nowait函式及異常捕獲

import multiprocessing
import time

if __name__ == '__main__':
    # 建立訊息佇列
    # 3: 表示訊息佇列最大個數
    queue = multiprocessing.Queue(3)
    # 放入資料
    queue.put(1)
    queue.put("abc")
    queue.put(["abc", "456"])
    # 佇列滿了在放入資料, 就不能放入資料了,直到訊息佇列有空閒位置才能再放入資料
    # queue.put(("34", 90))
    # put_nowait: 不會等待佇列有空閒位置再放入資料,如果資料放入不成功就直接崩潰
# queue.put_nowait(("34", 90)) # 建議: 放入資料使用put,因為比較安全不會崩潰 # 檢視佇列是否是滿的 # result = queue.full() # print(result) # 坑點: 只使用put放入資料直接判斷佇列是否為空獲取的結果不正確,因為沒有等佇列把資料寫完直接就取獲取了,那麼這是佇列是空的 # for i in range(10000): # print(i) # 解決辦法: 1. 延時一段時間 2. 通過個數去判斷 # time.sleep(0.001) #
if queue.qsize() == 0: # mac 版本不能使用qsize() print("佇列是空的") # result = queue.empty() # print(result) # 檢視佇列的個數 size = queue.qsize() print("訊息佇列個數:", size) # 獲取佇列的資料 value = queue.get() print(value) size = queue.qsize() print("訊息佇列個數:", size) # 獲取佇列的資料
value = queue.get() print(value) size = queue.qsize() print("訊息佇列個數:", size) # 獲取佇列的資料 value = queue.get() print(value) size = queue.qsize() print("訊息佇列個數:", size) # 佇列為空, 使用get會等待,直到佇列有資料以後再取值 # value = queue.get() # print(value) # 佇列為空,取值的時候不等待,但是取不到值那麼直接崩潰了 # value = queue.get_nowait() # print(value) # 建議: 獲取佇列的資料統一get,因為能保證程式碼不會有問題
  try:
        value = queue.get(timeout = 1)
    finally:
        print(value)
        size = queue.qsize()
        print("訊息佇列個數:", size)

        print("結束!")

當佇列為空時,再呼叫get函式,程式會阻塞,導致無法正常執行後面的程式碼,程式也不會退出,可以用get_nowait函式,當佇列為空,不會等待,直接丟擲異常,若想輸出後面的內容,可以用try…finally…捕獲異常執行。附:(timeout = 1可作為函式的引數)