- 主进程或等待子进程执行完
# 输出over后主进程内容已经执行完了,但是会等待子进程执行完
from multiprocessing import *
from time import *
def print_info():
for i in range(10):
print(i)
sleep(0.2)
if __name__ == '__main__':
p = Process(target=print_info)
p.start()
sleep(0.5)
print('over')
- 主进程强制子进程结束或直接结束程序
from multiprocessing import *
from time import *
def print_info():
for i in range(10):
print(i)
sleep(0.2)
if __name__ == '__main__':
p = Process(target=print_info)
# 把子进程设置为守护进程,主进程结束时子进程直接销毁
# p.daemon = True
p.start()
sleep(0.5)
# 退出主程序前先让子进程销毁
p.terminate()
print('over')