python thread

 python中得thread的一些机制和C/C++不同:在C/C++中,主线程结束后,其子线程会默认被主线程kill掉。而在python中,主线程结束后,会默认等待子线程结束后,主线程才退出。

        python对于thread的管理中有两个函数:join和setDaemon

  • join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。
  • setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的。

在这里给出一个例子:

import threading, time 
def doWaiting(): 
    print 'start waiting:', time.strftime('%H:%M:%S'
    time.sleep(30) 
    print 'stop waiting', time.strftime('%H:%M:%S'
thread1 = threading.Thread(target = doWaiting) 
thread1.setDaemon(True)
thread1.start() 
time.sleep(1)   
print 'start join',time.strftime('%H:%M:%S')
thread1.join(3)   

print 'end join',time.strftime('%H:%M:%S') 

posted @ 2013-10-15 19:01  taotaowill  阅读(368)  评论(0编辑  收藏  举报