Python Intro - Thread Series 01
Daemons are only useful when the main program is running, and it's okay to kill them off once the other non-daemon threads have exited. Without daemon threads, we have to keep track of them, and tell them to exit, before our program can completely quit. By setting them as daemon threads, we can let them run and forget about them, and when our program quits, any daemon threads are killed automatically.
Usually our main program implicitly waits until all other threads have completed their work. However, sometimes programs spawn a thread as a daemon that runs without blocking the main program from exiting. Using daemon threads is useful for services where there may not be an easy way to interrupt the thread or where letting the thread die in the middle of its work without losing or corrupting data. To designate a thread as a daemon, we call its setDaemon() method with a boolean argument. The default setting for a thread is non-daemon. So, passing True turns the daemon mode on.
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
def n():
logging.debug('Starting')
logging.debug('Exiting')
def d():
logging.debug('Starting')
time.sleep(5)
logging.debug('Exiting')
if __name__ == '__main__':
t = threading.Thread(name='non-daemon', target=n)
d = threading.Thread(name='daemon', target=d)
d.setDaemon(True)
d.start()
t.start()
To wait until a daemon thread has completed its work, we may want to use join() method.
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
def n():
logging.debug('Starting')
logging.debug('Exiting')
def d():
logging.debug('Starting')
time.sleep(5)
logging.debug('Exiting')
if __name__ == '__main__':
t = threading.Thread(name='non-daemon', target=n)
d = threading.Thread(name='daemon', target=d)
d.setDaemon(True)
d.start()
t.start()
d.join()
t.join()
The following code is using timeout argument (3 seconds) which is shorter than the sleep (5 seconds).
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
def n():
logging.debug('Starting')
logging.debug('Exiting')
def d():
logging.debug('Starting')
time.sleep(5)
logging.debug('Exiting')
if __name__ == '__main__':
t = threading.Thread(name='non-daemon', target=n)
d = threading.Thread(name='daemon', target=d)
d.setDaemon(True)
d.start()
t.start()
d.join(3.0)
print 'd.isAlive()', d.isAlive()
t.join()
posted on 2017-08-24 23:58 fanbird2008 阅读(37) 评论(0) 收藏 举报
浙公网安备 33010602011771号