gpt4 book ai didi

Python的multiprocessing.Queue + Process : Properly terminating both programs

转载 作者:行者123 更新时间:2023-12-02 00:28:46 25 4
gpt4 key购买 nike

给定这个 Python 程序:

# commented out code are alternatives I tried that don't work.

from multiprocessing import Process, Queue
#from multiprocessing import Process, JoinableQueue as Queue

def start_process(queue):
# queue.cancel_join_thread()
while True:
print queue.get()

if __name__ == '__main__':
queue = Queue()
# queue.cancel_join_thread()

process = Process(target=start_process, args=(queue,))
process.start()

queue.put(12)
process.join()

当我用 CTRL-C 终止这个程序时,会发生这种情况:

$> python queuetest.py
12
^CTraceback (most recent call last):
File "queuetest.py", line 19, in <module>
process.join()
File ".../python2.7/multiprocessing/process.py", line 119, in join
res = self._popen.wait(timeout)
Process Process-1:
File ".../python2.7/multiprocessing/forking.py", line 122, in wait
Traceback (most recent call last):
return self.poll(0)
File ".../python2.7/multiprocessing/forking.py", line 107, in poll
pid, sts = os.waitpid(self.pid, flag)
File ".../python2.7/multiprocessing/process.py", line 232, in _bootstrap
KeyboardInterrupt
self.run()
File ".../python2.7/multiprocessing/process.py", line 88, in run
self._target(*self._args, **self._kwargs)
File "queuetest.py", line 9, in start_process
print queue.get()
File ".../python2.7/multiprocessing/queues.py", line 91, in get
res = self._recv()
KeyboardInterrupt

.. 如何根据信号正确终止两个进程?

我想要实现的目标:在我的非最小化程序中,第二个进程拥有一个 SocketServer 并且需要一个额外的交互式命令行界面。

最佳答案

一种解决方案是通过队列发送特定消息(例如我的示例中的“exit”字符串),以正常终止工作程序(子进程)。由于 CTRL-C 信号发送给所有 child ,我们需要忽略它。这是示例代码:

from multiprocessing import Process, Queue

def start_process(queue):
while True:
try:
m = queue.get()
if m == 'exit':
print 'cleaning up worker...'
# add here your cleaning up code
break
else:
print m
except KeyboardInterrupt:
print 'ignore CTRL-C from worker'


if __name__ == '__main__':
queue = Queue()

process = Process(target=start_process, args=(queue,))
process.start()

queue.put(12)

try:
process.join()
except KeyboardInterrupt:
print 'wait for worker to cleanup...'
queue.put('exit')
process.join()

## or to kill anyway the worker if is not terminated after 5 seconds ...
## process.join(5)
## if process.is_alive():
## process.terminate()

关于Python的multiprocessing.Queue + Process : Properly terminating both programs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7827290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com