python中threading的setDaemon、join的用法

Mr.Bai 801 浏览 0

python中threading的setDaemon、join的用法

python 中的thread的一些机制:python 主线程结束后,会默认等待子线程结束后,主线程才退出。

#coding=utf-8
import threading
from time import ctime,sleep

def music(func):
        for i in range(2):
                print "I was listening to %s. %s" %(func,ctime())
                sleep(1)

def move(func):
        for i in range(2):
                print "I was at the %s ! %s" %(func,ctime())
                sleep(5)


threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)

if __name__ == '__main__':
        for t in threads:
                #t.setDaemon(True)
                t.start()
        #t.join()
        print "all over %s" %ctime()

运行结果如下:

I was listening to 爱情买卖. Mon Mar 13 11:51:55 2017

I was at the 阿凡达 ! Mon Mar 13 11:51:55 2017

all over Mon Mar 13 11:51:55 2017

I was listening to 爱情买卖. Mon Mar 13 11:51:56 2017

I was at the 阿凡达 ! Mon Mar 13 11:52:00 2017

[Finished in 10.1s]



主线程 all over Mon Mar 13 11:51:55 2017 已经结束了,但是子线程还在继续运行。

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

join: 如果在一个线程B中调用b.join(),则在b结束后,b才会接着b.join()往后运行

setDaemon: 主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死。

if __name__ == '__main__':
        for t in threads:
                t.setDaemon(True)
                t.start()
        #t.join()
        print "all over %s" %ctime()

运行结果:

I was listening to 爱情买卖. Mon Mar 13 11:56:38 2017

I was at the 阿凡达 ! Mon Mar 13 11:56:38 2017

all over Mon Mar 13 11:56:38 2017

[Finished in 0.1s]



all over Mon Mar 13 11:56:38 2017 主线程结束后,不在有输出

如果想让子线程运行完毕,那么添加join方法

if __name__ == '__main__':
        for t in threads:
                t.setDaemon(True)
                t.start()
        t.join()
        print "all over %s" %ctime()

输出如下:

I was listening to 爱情买卖. Mon Mar 13 11:58:08 2017

I was at the 阿凡达 ! Mon Mar 13 11:58:08 2017

I was listening to 爱情买卖. Mon Mar 13 11:58:09 2017

I was at the 阿凡达 ! Mon Mar 13 11:58:13 2017

all over Mon Mar 13 11:58:18 2017

[Finished in 10.1s]

发表评论 取消回复
表情 图片 链接 代码

分享
请选择语言