python realize daemon, a daemon thread, the guardian of the non-parallel Guardian

@ This article comes from public number: csdn2299, like the number of programmers can focus on public institutions

This article describes a method to achieve python daemon, a daemon thread, the guardian of non-daemon parallel, a detailed description of the guardian of the child, non-child daemon exist, the guardian of the child thread the non-guardian of the child process coexist, has a certain reference value, small partners who are interested can refer to
the daemon

1, guardian of the child

Master daemon process to create
one: daemon will terminate after the end of the main process code execution
Second: Could not open a sub-process within the daemon, or throw an exception: AssertionError: daemonic processes are not allowed to havechildren
Note: the process of inter are independent from each other, the end of the main process code running daemon immediately terminated

We look at an example

from multiprocessing import Process
import os,time,random
 
def task():
  print('%s is running' %os.getpid())
  time.sleep(2)
  print('%s is done' %os.getpid())
 
  #守护进程内无法再开启子进程,否则抛出异常
  # p = Process(target=time.sleep, args=(3,))
  # p.start()
 
if __name__ == '__main__':
  p=Process(target=task)
  p.daemon = True #1、必须在p.start()之前
  p.start()
  print('主')

Output:

The reason: the main process program starts to execute child process p, due to the need to open up the sub-process memory space, the need for time-consuming, so the main output process will first "master", since the main process is finished, it will be the guardian of the child p killed, along with the main process will quit

If the above code is modified as follows, plus p.join () This line of code

if __name__ == '__main__':
  p=Process(target=task)
  p.daemon = True #1、必须在p.start()之前
  p.start()
  p.join()
  print('主')

Then the program outputs the following:

14732 is running

14732 is done

join previously analyzed, it is to play the role of blocking, the child process is finished, before the implementation of the main process, so together join
1, executed to join, is to play the role of blocking, will execute child process, then finished in the execution the main process
2, can also be understood, executed to join, because the primary process print ( "master") is not executed, so the daemon will not be killed, to continue

1, guardian of the child, non-child daemon coexist

In the above example is only one child process daemon, finished in the main process, the guardian of the child will be killed, we look at a child process both the guardian of the child, but also contains a non-guardian of the child

from multiprocessing import Process
from threading import Thread
import time,os
def 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-------")

Output is as follows:

main-------
456
end456

For the following reasons: Because p1, p2 are sub-process, need to open up the memory space, it takes time, it will give priority to the output of the main process "main", due p1 is the guardian of the child, p2 non-guardian of the child, when the main process is finished (note like the main process has not quit, because there are non-daemon p2), p1 daemon it back, but there is a non-p2 daemon, so p2 will execute their own code tasks, when p2 is finished, the master also withdrew from the process, and then withdrew from the entire program

Daemon thread

Guardian of the child thread

Whether it is a process or thread, follow: Guardian xxx xxx will wait after the main run is complete destruction
needs to be emphasized: not finished running terminates

1. primary process, the operation is completed refers to the main process code has finished running
2 to the main thread, the run is completed refers to all non-daemon threads within a process where all the main thread has finished running, considered the main thread running complete

Detailed explanation:
1 main process after the end of its code has finished running the count (daemon was recovered at this point), then the main process will always wait for the child process after recycling non-guardian of the child process will run to completion (otherwise will produce zombie process), will end,

2 other non-main thread after the thread has finished running daemon considered finished running (daemon thread is recovered at this point). Since the end of the end of the process means that the main thread, the whole process will be recycled resources, and the process must be guaranteed to end after non-daemon threads have finished running.

Let's look at an example

from multiprocessing import Process
from threading import Thread
import os,time,random
def task():
  # t=Thread(target=time.sleep,args=(3,))
  # t.start()
  print('%s is running' %os.getpid())
  time.sleep(2)
  print('%s is done' %os.getpid())
 
if __name__ == '__main__':
  t=Thread(target=task)
  t.daemon = True
  t.start()
  print('主')

Output is as follows:

13368 is running
主

The reason:
the guardian of the child thread execution to t, due to the number of days the main line of general-purpose thread a piece of memory, so there is a different process to create their own space, so I have to perform the task code output sub-process, the output print ( '% s is running' % os.getpid ()), due time.sleep (2), it will execute the main thread "main", then the main thread is finished, then even after two seconds, because the main thread is finished, then the child will daemon thread exit, so print ( '% s is done' % os.getpid ()) will not be executed

Guardian guardian of the child thread the non-child process exist

We look at an example to resolve sub-thread non-concurrent guard guardian of the child

from threading import Thread
import time
def foo():
  print(123)
  time.sleep(1)
  print("end123")
 
def bar():
  print(456)
  time.sleep(3)
  print("end456")
 
if __name__ == '__main__':
  t1=Thread(target=foo)
  t2 = Thread(target=bar)
 
  t1.daemon=True
 
  t2.start()
  t1.start()
  print("main-------")

Output is as follows:

456
123
main-------

end123

end456

The reason is:
T1 is the guardian of the child thread, t2 non-guardian of the child thread, the main thread with the use of a memory, it will output t1, t1 sub-thread task code, so the implementation 456,123 due t1, t2 have sleep time, so execution the main thread of code, and then the main thread, the run is completed refers to the main thread within a process where all non-daemon threads all finished running, the main thread is considered finished running, it will execute t1, t2 sleep after the task code, then the program exits.
We ask why t1 guardian of the child thread will execute the code after sleep, not to say that the main thread code is completed, a daemon thread is blown away yet? Here we must note that the main thread, the run is completed refers to all non-daemon threads within a process where all the main thread has finished running, the main thread is considered finished running, at the time t2 has not finished
really appreciate your reading
of the University of time select the self-python, found that eating a working computer basic bad loss, this is not educated
can not do, can only be acquired to make up, then opened his own counter-attack in the road outside the coding, continuous learning python core knowledge, in-depth knowledge of basic computer learning, organized, if you are unwilling to mediocrity, it is with me outside of coding, growing it!
In fact, there is not only technical, more technical stuff than those, for example, how to make a fine programmer, rather than "Cock wire", the programmer itself is a noble presence, ah, is not it? [ Click to join ] you want to want to be a noble person, come on!

Published 61 original articles · won praise 22 · views 40000 +

Guess you like

Origin blog.csdn.net/haoxun02/article/details/105316684