The main process will wait for all child processes to finish executing before exiting .
The main process exits and the child process is destroyed
adopt sub_process.daemon = True Realization
import multiprocessing
import time
def task():
while True:
print("waiting...")
time.sleep(1)
# standard python How to write it , Directly executed modules , You need to add the code to determine whether it is the main module
if __name__ == '__main__':
# Create child process
sub_process = multiprocessing.Process(target=task)
# Set the subprocess as the main daemon , After that, the main process exits the child process and is destroyed directly
sub_process.daemon = True
sub_process.start()
# Main process delay 5 Second
time.sleep(5)
print("over")
Running results :
sub_process.terminate()
import multiprocessing
import time
def task():
# for i in range(10):
while True:
print("waiting...")
time.sleep(1)
# standard python How to write it , Directly executed modules , You need to add the code to determine whether it is the main module
if __name__ == '__main__':
# Create child process
sub_process = multiprocessing.Process(target=task)
sub_process.start()
# Main process delay 10 Second
time.sleep(10)
# Before exiting the main process , Let the child process destroy first
sub_process.terminate()
print("over")Running results :