Python多线程中join与setDaemon

先看一段程序:


import threading,time
from time import sleep, ctime
def now() :
return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
print 'start loop', nloop, 'at:', now()
sleep(nsec)
print 'loop', nloop, 'done at:', now()
def main():
print 'starting at:',now()
threadpool=[] for i in xrange(3):
th = threading.Thread(target= test,args= (i,2))
threadpool.append(th)
#th.setDaemon(True)
for th in threadpool:
th.start()
print 'all Done at:', now()
if __name__ == '__main__':
main()

如果不加join和setDaemon的话,输出如下:

123

如果添加join(),输出如下:
for th in threadpool :
threading.Thread.join( th )

123

可以看到主线程是最后才结束的,join() 的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
然后我们添加一下setDeamon
for i in xrange(3):
th = threading.Thread(target= test,args= (i,2))
threadpool.append(th)
th.setDaemon(True)

123

可以看到主线程结束之后,子线程也会结束。
我们可以添加锁试验一下:

import threading,time
from time import sleep, ctime
def now() :
return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
mutex.acquire()
print 'start loop', nloop, 'at:', now()
sleep(nsec)
print 'loop', nloop, 'done at:', now()
mutex.release()
def main():
print 'starting at:',now()
threadpool=[] for i in xrange(3):
th = threading.Thread(target= test,args= (i,2))
threadpool.append(th)
#th.setDaemon(True)
for th in threadpool:
th.start()
for th in threadpool :
threading.Thread.join( th )
print 'all Done at:', now()
if __name__ == '__main__':
mutex = threading.Lock()
main()


输出如下:

123