[英]is_alive() always returns False when called on a Thread from inside multiprocessing.Process
[英]python multiprocessing after kill process give is_alive() status True
我已经阅读了 python(3.7) 文档以了解多处理的概念。 对于Process
对象,有两个方法terminate()
和kill
。 终止进程使用 SIGTERM 完成,终止进程使用 Unix 上的 SIGKILL 信号。
当我们终止进程并检查进程的is_alive()
状态时,它给出False
。 但是,当我使用 kill 并检查进程的状态时,它会给出is_alive()
状态为 True。 如果它与终止进程相同,我不知道为什么它在杀死进程后给出 True 。
def test():
print("in test method")
time.sleep(3)
if __name__ == '__main__':
p1 = Process(target=test)
p1.start() # start process
# kill process after 1 sec
time.sleep(1)
p1.kill()
print(p1.is_alive()) # why process alive status true when kill process
time.sleep(3)
print(p1.is_alive())
无论您使用kill
还是terminate
,这些方法都只会启动进程的终止。 然后,您必须使用join
等待进程完全终止(如果您尝试使用sleep
,您只是猜测进程完全终止需要休眠多长时间):
p1.kill()
p1.join() # wait for p1 to fully complete
print(p1.is_alive()) # prints False
我认为这是因为p1.kill()
和print(p1.is_alive())
函数之间的时间太短了。 所以我认为,在这个 kill 命令完成之前,解释器试图在屏幕上打印该进程是否仍然处于活动状态。
例如,如果您将p1.kill()
time.sleep(0.001)
放在p1.kill()
和print(p1.is_alive())
函数之间,则会打印False
值而不是True
值。
import time
from multiprocessing import Process
def test():
print("in test method")
time.sleep(3)
if __name__ == '__main__':
p1 = Process(target=test)
p1.start() # start process
# kill process after 1 sec
time.sleep(1)
p1.kill()
time.sleep(0.001) # Wait for p1.kill() function is finished.
print(p1.is_alive()) # why process alive status true when kill process
time.sleep(3)
print(p1.is_alive())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.