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

作者:thn_sweety 时间:2021-08-11 10:56:51 

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

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

来源:https://blog.csdn.net/thn_sweety/article/details/53539873

标签:python,多线程,守护线程,join
0
投稿

猜你喜欢

  • Python中pillow知识点学习

    2023-11-26 05:27:01
  • python中matplotlib实现随鼠标滑动自动标注代码

    2023-09-02 10:49:47
  • Flash连接服务器

    2008-06-15 07:19:00
  • js字符串日期yyyy-MM-dd转化为date示例代码

    2023-08-06 16:35:58
  • 浅析PHP中的字符串编码转换(自动识别原编码)

    2023-09-08 08:04:44
  • oracle 彻底删除方法

    2009-07-02 12:22:00
  • 处理SQL Server 2000的命名实例和多实例

    2009-01-19 13:28:00
  • 解决pycharm中opencv-python导入cv2后无法自动补全的问题(不用作任何文件上的修改)

    2023-08-24 00:25:21
  • 高考要来啦!用Python爬取历年高考数据并分析

    2021-06-10 04:08:25
  • Zen Coding: 一种快速编写HTML/CSS代码[译]

    2009-12-16 12:53:00
  • 用css+Javascript实现扫描线效果图片

    2007-11-08 19:12:00
  • php牛逼的面试题分享

    2023-11-20 19:31:35
  • MySQL数据库优化经验详谈

    2009-12-15 10:34:00
  • 使用 Python 实现微信群友统计器的思路详解

    2022-02-04 23:38:08
  • 比较详细PHP生成静态页面教程

    2023-10-14 18:54:31
  • 文字适度阅读的宽度或者字数

    2007-10-26 07:31:00
  • XMLHTTP资料

    2008-09-05 17:20:00
  • ASP Google的translate API代码

    2011-04-03 11:16:00
  • PHP 修改SESSION的生存时间案例详解

    2023-06-11 19:44:20
  • python基于BeautifulSoup实现抓取网页指定内容的方法

    2022-11-29 12:11:48
  • asp之家 网络编程 m.aspxhome.com