Python daemon thread usage instance

  • 2020-06-07 04:46:02
  • OfStack

This article provides an example of how to use Python daemon threads. To share for your reference, specific as follows:

If you set a thread to be a daemon thread, you are saying that the thread is unimportant and that you do not have to wait for the thread to exit when the process exits. If your main thread exits without waiting for the child threads to complete, set the daemon property for those threads. That is, before the thread starts (thread.start ()), the setDeamon () function is called to set the thread's daemon flag. (thread. setDaemon(True)) means that this thread is "unimportant."

If you want to wait for the child to finish before exiting, do nothing, or call thread.setDaemon (False) explicitly and set the value of daemon to false. The new child thread inherits the parent thread's daemon flag. The entire Python does not end until all non-daemon threads exit, that is, until no non-daemon threads exist in the process.

Take a look at this example:


import time
import threading
def fun():
  print "start fun"
  time.sleep(2)
  print "end fun"
print "main thread"
t1 = threading.Thread(target=fun,args=())
#t1.setDaemon(True)
t1.start()
time.sleep(1)
print "main thread end"

Results:


main thread
start fun
main thread end
end fun

Conclusion: The program exits while waiting for the subthread to finish.

Set setDaemon to True


import time
import threading
def fun():
  print "start fun"
  time.sleep(2)
  print "end fun"
print "main thread"
t1 = threading.Thread(target=fun,args=())
t1.setDaemon(True)
t1.start()
time.sleep(1)
print "main thread end"

Results:


main thread
start fun
main thread end

Conclusion: The program exits after the main thread is finished. Causes the child thread not to finish running.

More about Python related topics: interested readers to view this site "Python process and thread skills summary", "Python Socket programming skills summary", "Python data structure and algorithm tutorial" and "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.


Related articles: