对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聚类算法之凝聚层次聚类实例分析

Python聚类算法之凝聚层次聚类实例分析

本文实例讲述了Python聚类算法之凝聚层次聚类。分享给大家供大家参考,具体如下: 凝聚层次聚类:所谓凝聚的,指的是该算法初始时,将每个点作为一个簇,每一步合并两个最接近的簇。另外即使到...

Python面向对象编程中的类和对象学习教程

Python中一切都是对象。类提供了创建新类型对象的机制。这篇教程中,我们不谈类和面向对象的基本知识,而专注在更好地理解Python面向对象编程上。假设我们使用新风格的python类,它...

编写Python CGI脚本的教程

编写Python CGI脚本的教程

你是否想使用Python语言创建一个网页,或者处理用户从web表单输入的数据?这些任务可以通过Python CGI(公用网关接口)脚本以及一个Apache web服务器实现。当用户请求一...

Python中垃圾回收和del语句详解

Python中的垃圾回收算法是采用引用计数, 当一个对象的引用计数为0时, Python的垃圾回收机制就会将对象回收 a = "larry" b = a larry这个字符串对象,...

windows下python模拟鼠标点击和键盘输示例

需要先装pywin32,windows下调用winapi的接口 复制代码 代码如下:## _*_ coding:UTF-8 _*___author__ = 'shanl' import...