use*_*r89 3 multiprocessing python-2.7
我正在编写一些使用该multiprocessing
模块的代码.但是,由于我是新手,经常发生的是弹出一些错误,停止主应用程序.
但是,应用程序的子项仍然在运行,我pythonw
在任务管理器列表中获得了很长的运行进程列表.
发生错误后,我还能做些什么来确保所有子进程都被杀死?
这个难题有两个部分.
对于第1部分,您可以使用multiprocessing.active_children()
获取所有活动子项的列表并使用它们将其终止Process.terminate()
.请注意使用Process.terminate()
通常的警告.
from multiprocessing import Process
import multiprocessing
def f(name):
print 'hello', name
while True: pass
if __name__ == '__main__':
for i in xrange(5):
p = Process(target=f, args=('bob',))
p.start()
# At user input, terminate all processes.
raw_input("Press Enter to terminate: ")
for p in multiprocessing.active_children():
p.terminate()
Run Code Online (Sandbox Code Playgroud)
第2部分的一个解决方案是使用sys.excepthook
,如本答案中所述.这是一个组合的例子.
from multiprocessing import Process
import multiprocessing
import sys
from time import sleep
def f(name):
print 'hello', name
while True: pass
def myexcepthook(exctype, value, traceback):
for p in multiprocessing.active_children():
p.terminate()
if __name__ == '__main__':
for i in xrange(5):
p = Process(target=f, args=('bob',))
p.start()
sys.excepthook = myexcepthook
# Sleep for a bit and then force an exception by doing something stupid.
sleep(1)
1 / 0
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3833 次 |
最近记录: |