在无限循环中,停止连接到队列的python多处理工作器的最干净的方法是什么?

2024-03-28 15:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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 ...

那么,怎样才能干净地结束这样一个过程呢?


Tags: inimportsignalqueue进程defgeventmultiprocessing