python 多线程中的守护线程与join的用法

多线程:在同一个时间做多件事

守护线程:如果在程序中将子线程设置为守护线程,则该子线程会在主线程结束时自动退出,设置方式为thread.setDaemon(True),要在thread.start()之前设置,默认是false的,也就是主线程结束时,子线程依然在执行。

thread.join():在子线程完成运行之前,该子线程的父线程(一般就是主线程)将一直存在,也就是被阻塞

实例:

#!/usr/bin/python
# encoding: utf-8


import threading
from time import ctime,sleep

def func1():
    count=0
    while(True):
        sleep(1)
        print 'fun1 ',count
        count = count+1

def func2():
    count=0
    while(True):
        sleep(2)
        print 'fun2 ',count
        count = count+1

threads = []
t1 = threading.Thread(target=func1)
threads.append(t1)
t2 = threading.Thread(target=func2)
threads.append(t2)

if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()

上面这段程序执行后,将不会有任何输出,因为子线程还没来得及执行,主线程就退出了,子线程为守护线程,所以也就退出了。

修改后的程序:

#!/usr/bin/python
# encoding: utf-8


import threading
from time import ctime,sleep

def func1():
    count=0
    while(True):
        sleep(1)
        print 'fun1 '+str(count)
        count = count+1

def func2():
    count=0
    while(True):
        sleep(2)
        print 'fun2 '+str(count)
        count = count+1

threads = []
t1 = threading.Thread(target=func1)
threads.append(t1)
t2 = threading.Thread(target=func2)
threads.append(t2)

if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()
    t.join()

可以按照预期执行了,主要join的调用要加在循环外,不然程序只会执行第一个线程。

print 的部分改成+,是为了避免输出结果中出现类似fun1 fun2 49 这种情况,这是由于程序执行太快,用‘,’间隔相当于执行了两次print ,在这期间另一个线程也执行了print,所以导致了重叠。




  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值