我正在使用multiprocessing.Pool
和multiprocessing.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()
现在,当我尝试退出时,我得到以下状态:
futex(0x7f99d9188000, FUTEX_WAIT, 0, NULL ...
。那么干净地结束这样一个过程的正确方法是什么?
答案 0 :(得分:13)
我弄明白了这个问题。根据{{3}},pool
必须为close()ed
才能join()ed
。在pool.close()
之前添加pool.join()
解决了问题。