Python线程join和setDaemon
看一下线程的setDaemon()方法
import time
import threading
import ctypes
import inspect def sayHello():
for i in range(10):
print("hello")
time.sleep(1) def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread):
_async_raise(thread.ident, SystemExit) if __name__ == '__main__':
# sayHello()
t = threading.Thread(target=sayHello, args=())
t.setDaemon(True) # 主线程结束后停止子线程
t.start()
for i in range(3):
print(t.is_alive())
time.sleep(1)
上面的输出是:
hello
True
True
hello
hello
True
hello
我们修改一下代码:
import time
import threading
import ctypes
import inspect def sayHello():
for i in range(10):
print("hello")
time.sleep(1) def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread):
_async_raise(thread.ident, SystemExit) if __name__ == '__main__':
# sayHello()
t = threading.Thread(target=sayHello, args=())
t.setDaemon(False) # 主线程结束后不停止子线程
t.start()
for i in range(3):
print(t.is_alive())
time.sleep(1)
程序的输出是:
hello
True
True
hello
hello
True
hello
hello
hello
hello
hello
hello
hello
可见,setDaemon()方法就是决定在主线程结束后是否结束子线程,如果为True时,会结束子线程,为False时,不会结束子线程。
我们再来看join()方法:
直接看代码
import time
import threading
import ctypes
import inspect def sayHello():
for i in range(10):
print("hello")
time.sleep(1) def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread):
_async_raise(thread.ident, SystemExit) if __name__ == '__main__':
# sayHello()
t = threading.Thread(target=sayHello, args=())
t.setDaemon(False) # 主线程结束后不停止子线程
t.start()
for i in range(3):
print(t.is_alive())
time.sleep(1)
# t.join()
print("over")
输出结果为:
hello
True
True
hello
True
hello
hello
over
hello
hello
hello
hello
hello
hello
可以看到主线程结束时,打印出over,之后子线程还在继续打印hello
修改代码:
import time
import threading
import ctypes
import inspect def sayHello():
for i in range(10):
print("hello")
time.sleep(1) def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread):
_async_raise(thread.ident, SystemExit) if __name__ == '__main__':
# sayHello()
t = threading.Thread(target=sayHello, args=())
t.setDaemon(False) # 主线程结束后不停止子线程
t.start()
for i in range(3):
print(t.is_alive())
time.sleep(1)
t.join()
print("over")
输出结果为:
hello
True
hello
True
True
hello
hello
hello
hello
hello
hello
hello
hello
over
可以看到设置t.join()方法之后,主线程要等待t这个线程结束之后,才能继续,也就是等hello打印完之后才打印over。
Python线程join和setDaemon的更多相关文章
- python线程join
几个事实 1 python 默认参数创建线程后,不管主线程是否执行完毕,都会等待子线程执行完毕才一起退出,有无join结果一样 2 如果创建线程,并且设置了daemon为true,即thread.se ...
- Python多线程join和setDaemon区别与用法
一直没有太搞清楚join和setDaemon有什么区别,总是对于它们两个的概念很模糊,需要做个实验然后记录一下. 先说结论: join: 子线程合并到主线程上来的作用,就是当主线程中有子线程join的 ...
- python线程join方法
转载:http://www.cnblogs.com/cnkai/p/7504980.html Python多线程与多进程中join()方法的效果是相同的. 下面仅以多线程为例: 首先需要明确几个概念: ...
- python的threading.Thread线程的start、run、join、setDaemon
Pycharm整体看下Thread类的内容:模拟的是Java的线程模型 表示方法method,上面的锁头表示这个是类内部的方法,从方法名字命名规范可以看出,都是_和__开头的,一个下划线表示是子类可以 ...
- 关于python多线程编程中join()和setDaemon()的一点儿探究
关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的 ...
- Python中threading的join和setDaemon的区别及用法
Python多线程编程时经常会用到join()和setDaemon()方法,基本用法如下: join([time]): 等待至线程中止.这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或 ...
- python网络编程--线程join和Daemon(守护进程)
一:什么情况下使用join join([timeout])调用join函数会使得主调线程阻塞,直到被调用线程运行结束或超时. 参数timeout是一个数值类型,用来表示超时时间,如果未提供该参数,那么 ...
- Python中threading的join和setDaemon的区别及用法[例子]
Python多线程编程时,经常会用到join()和setDaemon()方法,今天特地研究了一下两者的区别. 1.join ()方法:主线程A中,创建了子线程B,并且在主线程A中调用了B.join() ...
- Python中threading的join和setDaemon的区别[带例子]
python的进程和线程经常用到,之前一直不明白threading的join和setDaemon的区别和用法,今天特地研究了一下.multiprocessing中也有这两个方法,同样适用,这里以thr ...
随机推荐
- 运维-kibana常用查询使用
1.登录服务器地址 http://kibana.ops.xxx.com.cn/ 查询语法: 支持 AND , OR, && || >,< ,=模糊 *,! 1.如查询n ...
- 缓存穿透 & 缓存击穿 & 缓存雪崩
参考文档: 缓存穿透和缓存失效的预防和解决:https://blog.csdn.net/qq_16681169/article/details/75138876 缓存穿透 缓存穿透是指查询一个一定不存 ...
- MySQL基础概念知多少
MySQL基础概念相关的名词还是挺多的,比如3大范式.4种隔离界别.ACID.DQL.DML.DDL,还有redo.undo.binlog等,本文就统一整理下MySQL常见的基础概念,方便小伙伴们翻阅 ...
- ASP.NET Core Swagger接入使用IdentityServer4 的 WebApi
写在前面 是这样的,我们现在接口使用了Ocelot做网关,Ocelot里面集成了基于IdentityServer4开发的授权中心用于对Api资源的保护.问题来了,我们的Api用了SwaggerUI做接 ...
- 学Redis这篇就够了!
学Redis这篇就够了! 作者:王爷科技 https://www.toutiao.com/i6713520017595433485 Redis 简介 & 优势 Redis 数据类型 发布订 ...
- centos 6.9 安装docker
1.查看系统具体版本 yum install lsb -y lsb_release -a 2.安装yum源 yum -y install http://dl.fedoraproject.org/pub ...
- kali 触摸板手势之fusuma
1.执行如下命令进行安装 *fusuma 需要在ruby环境下运行,若计算机不支持ruby,则先执行:apt-get install ruby apt-get update apt-get insta ...
- AQS4源码
@SuppressWarnings("restriction") public abstract class AbstractQueuedSynchronizer1 extends ...
- [转帖]分布式锁-redLock And Redisson
分布式锁-redLock And Redisson 2019-03-01 16:51:48 淹不死的水 阅读数 372更多 分类专栏: 分布式锁 版权声明:本文为博主原创文章,遵循CC 4.0 B ...
- 《即时消息技术剖析与实战》学习笔记3——IM系统如何保证消息的实时性
IM 技术经历过几次迭代升级,如图所示: 从简单.低效的短轮询逐步升级到相对效率可控的长轮询: 全双工的 Websocket 彻底解决了服务端的推送问题: 基于 TCP 长连接衍生的 IM 协议,能够 ...