我有以下测试代码子类化multiprocessing的过程:
import multiprocessing as mp
class TestProcess(mp.Process):
def __init__(self,name):
super().__init__()
self.name = name
def run(self):
while True:
print('{} says "I am alive"'.format(self.name))
if __name__ == "__main__" :
procs = [TestProcess(i) for i in list('ABC')]
try:
for p in procs:
print('starting {}'.format(p.name))
p.start()
except KeyboardInterrupt:
print('caught interrupt')
except Exception as e:
print(str(e))
finally:
for p in procs:
print('stopping {}'.format(p.name))
p.terminate()
由于某种原因A提前终止而没有发送 ctrl + c 并且进程B和C似乎永远不会运行:
host:~ user$ python process_example.py
starting A
starting B
starting C
A says "I am alive"
[... x 16 lines]
A says "I am alistopping A
stopping B
stopping C
如果有人能够解释这一点,我会非常感激。
更新
感谢所有人的迅速回应;我已更新到以下内容:
import time
import multiprocessing as mp
class TestProcess(mp.Process):
def __init__(self,name):
super().__init__()
self.name = name
def run(self):
while True:
print('{} says "I am alive"'.format(self.name))
time.sleep(1)
if __name__ == "__main__" :
procs = [TestProcess(i) for i in list('ABC')]
try:
for p in procs :
print('starting {}'.format(p.name))
p.start()
for p in procs :
print('joining {}'.format(p.name))
p.join()
except KeyboardInterrupt:
print('caught interrupt')
except Exception as e:
print(str(e))
finally:
for p in procs :
print('stopping {}'.format(p.name))
p.terminate()
现在我明白了:
host:~ user$ python process_example.py
starting A
starting B
starting C
A says "I am alive"
joining A
B says "I am alive"
C says "I am alive"
A says "I am alive"
B says "I am alive"
C says "I am alive"
A says "I am alive"
B says "I am alive"
C says "I am alive"
A says "I am alive"
B says "I am alive"
C says "I am alive"
A says "I am alive"
B says "I am alive"
C says "I am alive"
B says "I am alive"
A says "I am alive"
C says "I am alive"
^Ccaught interrupt
stopping A
stopping B
stopping C
所以只需加入一个线程吗?
答案 0 :(得分:3)
我不清楚你对此的期望是什么。启动进程后,代码立即进入finally:
块并显式终止所有进程。所以他们当然会停下来。
至于为什么只有“A”表示它还活着,这可能因平台(OS)而异。您的run()
方法只是一个“忙碌循环”,尽可能快地打印。在启动它们之后很快就会杀死这些进程,在你的平台上,操作系统永远不会在你终止它们之前为其他进程安排时间片。
尝试,例如,在启动进程的循环之后粘贴time.sleep(10)
。这将延迟杀死进程10秒,这可能足以让B
和C
在操作系统被杀之前得到一些爱;-)。