[英]What is the cleanest way to stop a python multiprocessing worker attached to a queue in an infinite loop?
我正在使用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 ...
那么干凈地結束這樣一個過程的正確方法是什么?
我解決了這個問題。 根據對文檔multiprocessing.Pool.join()
pool
必須close()ed
可之前join()ed
。 添加pool.close()
之前pool.join()
解決了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.