簡體   English   中英

在無限循環中停止連接到隊列的python多處理工作程序的最簡潔方法是什么?

[英]What is the cleanest way to stop a python multiprocessing worker attached to a queue in an infinite loop?

我正在使用multiprocessing.Poolmultiprocessing.Queue在python中實現生產者 - 消費者模式。 消費者是使用gevent生成多個任務的預分叉進程。

這是一個精簡版的代碼:

import gevent
from Queue import Empty as QueueEmpty
from multiprocessing import Process, Queue, Pool
import signal
import time

# Task queue
queue = Queue()

def init_worker ():
    # Ignore signals in worker
    signal.signal( signal.SIGTERM, signal.SIG_IGN )
    signal.signal( signal.SIGINT, signal.SIG_IGN )
    signal.signal( signal.SIGQUIT, signal.SIG_IGN )

# One of the worker task
def worker_task1( ):
    while True:
        try:
            m = queue.get( timeout = 2 )

            # Break out if producer says quit
            if m == 'QUIT':
                print 'TIME TO QUIT'
                break

        except QueueEmpty:
            pass

# Worker
def work( ):
    gevent.joinall([
        gevent.spawn( worker_task1 ),
    ])

pool = Pool( 2, init_worker )
for i in xrange( 2 ):
    pool.apply_async( work )

try:
    while True:
        queue.put( 'Some Task' )
        time.sleep( 2 )

except KeyboardInterrupt as e:
    print 'STOPPING'

    # Signal all workers to quit
    for i in xrange( 2 ):
        queue.put( 'QUIT' )

    pool.join()

現在當我嘗試退出它時,我得到以下狀態:

  1. 父進程正在等待其中一個子進程加入。
  2. 其中一個孩子處於不復存在的狀態。 完成但父母正在等待其他孩子完成。
  3. 其他孩子正在顯示: futex(0x7f99d9188000, FUTEX_WAIT, 0, NULL ...

那么干凈地結束這樣一個過程的正確方法是什么?

我解決了這個問題。 根據對文檔multiprocessing.Pool.join() pool必須close()ed可之前join()ed 添加pool.close()之前pool.join()解決了這個問題。

暫無
暫無

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

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