天天看點

Python多程序 主程序結束前如何銷毀子程序

Python多程序 主程序結束前如何銷毀子程序

因為一般子程序不結束,主程序也不會結束

有兩種方式可以解決該問題

import multiprocessing

import time

def task():

while True:
    print("任務執行中")
    time.sleep(0.2)           

if name == '__main__':

sub_task = multiprocessing.Process(target=task)
# 把子程序設定為守護主程序
# sub_task.daemon = True
sub_task.start()

time.sleep(0.5)
# 主程序結束前 先銷毀子程序
sub_task.terminate()
print("主程序結束了")