我有一个使用多处理Process类启动进程的python脚本。在该过程中,我使用无限循环启动线程,并通过执行exit(1)在主线程上模拟异常。我原以为退出会杀死该进程,但事实并非如此,主线程将其报告为活动状态。
我尝试了引发异常和调用exit的方法,但是没有任何效果。 我尝试通过等待is_alive和调用join来等待该过程完成。但是两者具有相同的行为。
from multiprocessing import Process
from threading import Thread
from time import sleep
def infinite_loop():
while True:
print("It's sleeping man")
sleep(1)
def start_infinite_thread():
run_thread = Thread(target=infinite_loop)
run_thread.start()
exit(1)
def test_multi():
x = Process(target=start_infinite_thread)
x.start()
sleep(5)
assert not x.is_alive()
我希望该过程不会生效,但是断言会失败。
答案 0 :(得分:0)
感谢@Imperishable Night,通过将线程设置为守护程序测试通过来进行回复。 有效的代码:
from multiprocessing import Process
from threading import Thread
from time import sleep
def infinite_loop():
while True:
print("It's sleeping man")
sleep(1)
def start_infinite_thread():
run_thread = Thread(target=infinite_loop)
run_thread.daemon = True
run_thread.start()
exit(1)
def test_multi():
x = Process(target=start_infinite_thread)
x.start()
sleep(1)
assert not x.is_alive()