Skip to content

chapter3.5 如何杀掉一个进程 #88

Description

@Bestporter

文中说到terminate会立即杀死进程,但是输出如下下方的图,在p.terminate()之后,输出进程p.is_alive()返回了True,也就是进程还活着,但是在p.join()之后,再次输出p进程的状态却死了,经过自己尝试,terminate确实会立即去杀死进程,但是在主进程执行到p.is_alive()的时候p尚未被杀死所以导致了返回了True。看文章的时候我以为是和后面的join有关,后面尝试在terminate之后执行time.sleep(),发现与join并无关联。具体代码如下:

import multiprocessing
from multiprocessing.dummy import Process
import time

def foo():
    print("Starting func")
    time.sleep(0.1)

if __name__ == "__main__":
    p  = multiprocessing.Process(target=foo)
    print("Process before excution:", p, p.is_alive())
    p.start()
    print("Process running :", p.is_alive())
    p.terminate()
    time.sleep(0.1) # 如果没有这一行,下面一行的代码可能会返回True
    print("Process terminated:" , p.is_alive()) # process is alive
    p.join()
    print("Process joined:", p.is_alive()) # process is dead

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions