setdaemon守护进程
#_*_coding:utf-8_*_ __author__ = ‘gaogd‘ import time import threading ‘‘‘ 守护进程,如果主线程down了,子线程也就没有了。 下面先通过主进程生成main主线程,之后main主线程再生成10个子线程。 ‘‘‘ ‘‘‘ def run(num): if not num == 5: time.sleep(1) print ‘Hi, I am thread %s..lalala\n‘ % num def main(n): print "----running main thread-----" for i in range(n):#10 t = threading.Thread(target=run,args=(i,)) t.start() time.sleep(3) print "-----done main thread -------" main_thread = threading.Thread(target=main,args=(10,)) #main_thread.setDaemon(True) main_thread.start() time.sleep(2) print ‘\n----->>>>‘ #main_thread.join(timeout=1) ‘‘‘ def run(num): if not num == 5: time.sleep(1) print ‘Hi, I am thread %s..lalala\n‘ % num def main(n): print "----running main thread-----" for i in range(n):#10 t = threading.Thread(target=run,args=(i,)) t.start() time.sleep(3) print "-----done main thread -------" main_thread = threading.Thread(target=main,args=(100,)) main_thread.setDaemon(True) ##这里的意思就是把主进程设置为守护进程 main_thread.start() time.sleep(2) print ‘\n----->>>>‘ #main_thread.join(timeout=1)
本文出自 “奋斗吧” 博客,请务必保留此出处http://lvnian.blog.51cto.com/7155281/1852963
原文地址:http://lvnian.blog.51cto.com/7155281/1852963