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

yipeiwu_com5年前Python基础

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

守护线程:如果在程序中将子线程设置为守护线程,则该子线程会在主线程结束时自动退出,设置方式为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,所以导致了重叠。

以上这篇对python 多线程中的守护线程与join的用法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈Python中的可迭代对象、迭代器、For循环工作机制、生成器

浅谈Python中的可迭代对象、迭代器、For循环工作机制、生成器

1.iterable iterator区别 要了解两者区别,先要了解一下迭代器协议: 迭代器协议是指:对象需要提供__next__()方法,它返回迭代中的元素,在没有更多元素后,抛出St...

python tensorflow基于cnn实现手写数字识别

一份基于cnn的手写数字自识别的代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- import tensorflow as tf from tenso...

异步任务队列Celery在Django中的使用方法

异步任务队列Celery在Django中的使用方法

前段时间在Django Web平台开发中,碰到一些请求执行的任务时间较长(几分钟),为了加快用户的响应时间,因此决定采用异步任务的方式在后台执行这些任务。在同事的指引下接触了Celery...

Win8.1下安装Python3.6提示0x80240017错误的解决方法

Win8.1下安装Python3.6提示0x80240017错误,如何解决? 定位原因 缺少Windows补丁KB2999226 解决方法 到Microsoft Download Cen...

django的csrf实现过程详解

django的csrf实现过程详解

如果是ajax提交,可以按照下面的方式处理 <script src="/static/jq/jquery-3.3.1.js"></script> <s...