Previous Post IntroductionThe role of join in multiprocessing, this article continues to learn the impact of setting up daemon's on a program. (Python bulls can go around).
We illustrate this with two examples
# encoding: utf-8 """ author: yangyi@ time: 2019/7/30 11:20 AM func: """ from multiprocessing import Process import os import time def now(): return str(('%Y-%m-%d %H:%M:%S', ())) def func_1(name): print(now() + ' Run child process %s ,pid is %s...' % (name, ())) (2) print(now() + ' Stop child process %s ,pid is %s...' % (name, ())) def func_2(name): print(now() + ' Run child process %s , pid is %s...' % (name, ())) (4) print(now() + ' hello world!') print(now() + ' Stop child process %s , pid is %s...' % (name, ())) if __name__ == '__main__': print ('Parent process %s.' % ()) p1 = Process(target=func_1, args=('func_1',)) p2 = Process(target=func_2, args=('func_2',)) print now() + ' Process start.' = True # Set child process p1 as daemon thread () () print now() + ' Process end .'
The results show that
Started child process Run child process func_1 but no end prompt for func_1. It ends with the end of the main process.
if __name__ == '__main__': print ('Parent process %s.' % ()) p1 = Process(target=func_1, args=('func_1',)) p2 = Process(target=func_2, args=('func_2',)) print now() + ' Process start.' = True #Set child process p2 as daemon thread () () print now() + ' Process end .'
The results show that
The child process func_1 is started, and func_2 is terminated without starting it, as the main process is terminated.
summarize
Setting join() for a process or a sub-thread means that the current program must wait until the sub-process or sub-thread finishes running. When we run a main process (main thread) in a program, then there are multiple sub-threads created. The main thread and the child threads are executed separately. When the main thread wants to exit the program it checks if the child threads are finished. If we set the deamon attribute to True, the main thread will be terminated along with the sub-threads, regardless of whether the sub-threads are terminated or not.
-The End-
Above is the detailed content of how to set up daemons in python, for more information about python daemons, please pay attention to my other related articles!