A daemon process
The main process creates the child process and then sets the process to guard its own process
There are two points to emphasize about Daemons:
One: The daemon terminates after the execution of the main process code is completed
Second: The daemon can no longer open the child process, or throw an exception: Assertionerror:daemonic processes is not allowed to has children
If we have two tasks need to execute concurrently, then open a main process and a child process to execute separately is OK, if the child process of the task after the end of the main process is not necessary to exist, then the child process should be set to the daemon before opening. The daemon terminates after the main process code runs
#!/usr/bin/env python#-*-coding:utf-8-*- fromMultiprocessingImportProcessImport TimedefTask (name):Print('%s is piaoing'%name) Time.sleep (3) Print('%s is Piao end'%name)if __name__=='__main__': P=process (target=task,args= ('Xiaojiu',)) P.daemon=true#be sure to set up before P.start (), set p to daemon, prevent p from creating child processes, and the parent process Code execution ends, p terminates the runP.start ()Print('Master')#as soon as the terminal prints out the line, the daemon p will end up.#OutputMain
Two exercises
Think about what might happen with the following code execution results? Why?
from multiprocessing import Processimport timedef foo(): print(123) time.sleep(1) print("end123")def bar(): print(456) time.sleep(3) print("end456")if __name__ == ‘__main__‘: p1=Process(target=foo) p2=Process(target=bar) p1.daemon=True p1.start() p2.start() print("main-------")
#输出
Main-------
456
end456
Because the main process is dead, P1 is dead,
Concurrent Programming (daemon)