Terminate() function of python multi-process process

Terminate() function of python multi-process process

The terminate() function is used to kill the child process.
Examples are as follows:

from multiprocessing import Process
import time

def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


if __name__ == "__main__":
    # 在windows环境下,开启进程必须在__name__ == "__main__"下面
    p = Process(target=task,args=("常辛",))  # 创建一个进程对象
    p.start()
    
    p.terminate()  # 杀死子进程
    
    print("主开始")


主开始

Here we use print(p.is_alive()) to determine whether the child process exists

from multiprocessing import Process
import time


def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


if __name__ == "__main__":
    # 在windows环境下,开启进程必须在__name__ == "__main__"下面
    p = Process(target=task, args=("常辛",))  # 创建一个进程对象
    p.start()

    p.terminate()  # 杀死子进程
    print(p.is_alive())  # 判断子进程是否活着

    print("主开始")

True
主开始

Very surprised, it turned out to be True. This may be because the program hasn't reacted yet. Let's add time.sleep() and take a look:

from multiprocessing import Process
import time


def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


if __name__ == "__main__":
    # 在windows环境下,开启进程必须在__name__ == "__main__"下面
    p = Process(target=task, args=("常辛",))  # 创建一个进程对象
    p.start()

    p.terminate()  # 杀死子进程
    time.sleep(1)
    print(p.is_alive())  # 判断子进程是否活着

    print("主开始")

False
主开始

The judgment here is False, and the result is correct. In addition, p.join() can also be used instead of time.sleep(), and the execution result is the same:

from multiprocessing import Process
import time


def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


if __name__ == "__main__":
    # 在windows环境下,开启进程必须在__name__ == "__main__"下面
    p = Process(target=task, args=("常辛",))  # 创建一个进程对象
    p.start()

    p.terminate()  # 杀死子进程
    # time.sleep(1)
    p.join()
    print(p.is_alive())  # 判断子进程是否活着

    print("主开始")

False
主开始

By the way, in multi-process, p has its own name attribute (Process-1 by default):

from multiprocessing import Process
import time


def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


if __name__ == "__main__":
    # 在windows环境下,开启进程必须在__name__ == "__main__"下面
    p = Process(target=task, args=("常辛",))  # 创建一个进程对象
    p.start()

    print(p.name)

    print("主开始")

Process-1
主开始
常辛 is running
常辛 is gone

If you want to modify the default name attribute, change
p = Process(target=task, args=("常辛",))
to:
p = Process(target=task,args=("常辛",) ,name = "xiao")
, the p.name output here is xiao

Guess you like

Origin blog.csdn.net/m0_50481455/article/details/113749690