簡體   English   中英

python3 queue.put() 阻塞 main

[英]python3 queue.put() blocking main

當隊列大小超過特定值(1386)時,python3 queue.put() 將阻塞主進程。

我使用 30 個子進程和兩個隊列來計算一個 int 數,每個子進程從第一個隊列中獲取數字,然后將這個數字放入第二個隊列。 我可以看到所有子進程都成功關閉,但主進程被阻止。 重要的是,當數字長度小於 1387 時,它工作得很好。 蟒蛇版本 3.7.0

    #!/usr/bin/env python
from multiprocessing import Manager, Process, Lock, Queue


def work(q_in, o_out, process, lock):
    print("process ", process, "start")
    while 1:
        lock.acquire()
        if q_in.empty():
            lock.release()
            break
        d1 = q_in.get(timeout=1)
        o_out.put(d1*2)
        print("in process ", process, " queue 2 size", o_out.qsize())
        lock.release()
    print("process ", process, "done")


if __name__ == '__main__':
    length = 1386
    q_in = Queue(length)
    q_out = Queue(length)
    for i in range(length):
        q_in.put(i)
    lock = Lock()
    processes = list()
    for i in range(30):
        p = Process(target=work, args=(q_in, q_out, i, lock))
        processes.append(p)
        p.start()
    [p.join() for p in processes]
    print("main done")

當長度小於 1386 時,我可以看到“主完成”,但長度 = 1387,所有子進程都關閉但“主完成”從不顯示,主進程保持運行狀態

問題在於,沒有什么消耗q_out的數據。 工人能夠完成他們的工作,因為隊列在他們的一邊被緩沖,但是(某些)進程保持活動狀態,等待能夠將數據刷新到底層管道。 有關更多詳細信息,請參見https://bugs.python.org/issue29797

根據您的情況,管道似乎能夠在其緩沖區中容納1386個項目。

您可以使用 put_nowait() ,只要達到 maxsize 就會引發 queue.full 異常。 您可以從此處獲取更多詳細信息

import Queue 
q = Queue.Queue(1) 
q.put_nowait("a")

try:
    q.put_nowait("b")
except Queue.Full:
    print "Queue is full."

來源 - https://www.kite.com/python/docs/queue.Queue.put_nowait

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM