python 多线程 setdaemon_Python线程join和setDaemon
看一下线程的setDaemon()方法
importtimeimportthreadingimportctypesimportinspectdefsayHello():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 notinspect.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")defstop_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
我们修改一下代码:
importtimeimportthreadingimportctypesimportinspectdefsayHello():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 notinspect.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")defstop_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()方法:
直接看代码
importtimeimportthreadingimportctypesimportinspectdefsayHello():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 notinspect.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")defstop_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
修改代码:
importtimeimportthreadingimportctypesimportinspectdefsayHello():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 notinspect.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")defstop_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 多线程 setdaemon_Python线程join和setDaemon相关推荐
- Python 多线程中的 join() 和 setDaemon()
Demo 是最好的老师!!! 参考链接:Python多线程与多线程中join()的用法 - cnkai - 博客园 知识点一(setDaemon(False)): 当一个进程启动之后,会默认产生一个主 ...
- python 多线程 setdaemon_python使用Thread的setDaemon启动后台线程教程
多线程编程当中, 线程的存在形态比较抽象. 通过前台线程后台线程, 可以有效理解线程运行顺序.(复杂的多线程程序可以通过设置线程优先级实现) 后台线程与前台线程的直接区别是, 1)setDaemon( ...
- Python中threading的join和setDaemon的区别及用法 例子
Python中threading的join和setDaemon的区别及用法 Python多线程编程时,经常会用到join()和setDaemon()方法,今天特地研究了一下两者的区别. 1.join ...
- php和python的多线程,Python多线程以及线程锁简单理解(代码)
本篇文章给大家带来的内容是关于Python多线程以及线程锁简单理解(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 多线程threading 模块创建线程创建自己的线程类线程通 ...
- python多线程结束线程_Python多线程和Office第2部分
python多线程结束线程 This is the second and final part of the series. You can find the first part of the bl ...
- python多线程守护线程_Python守护程序线程
python多线程守护线程 In this tutorial we will be learning about Python Daemon Thread. In our previous tutor ...
- python多线程结束线程_Python线程– Python多线程
python多线程结束线程 Python threading module is used to implement multithreading in python programs. In thi ...
- python 多线程 setdaemon_Python多线程join和setDaemon区别与用法
一直没有太搞清楚join和setDaemon有什么区别,总是对于它们两个的概念很模糊,需要做个实验然后记录一下. 先说结论: join: 子线程合并到主线程上来的作用,就是当主线程中有子线程join的 ...
- python threading setdaemon_Python线程为什么搞个setDaemon
渣渣飞 渣渣飞,长年在票圈深夜放毒,是网易游戏高级运维工程师,对代码性能及系统原理饶有兴趣,三人行,必有我师.现负责监控相关业务开发. 前言 使用 Python 都不会错过线程这个知识,但是每次谈到线 ...
最新文章
- 资源 | 10x Python开发者必读:本月Python文章TOP 10
- Windows核心编程 第八章 用户方式中线程的同步(下)
- c语言函数汉诺塔不用move,C语言——汉诺塔问题(函数递归)
- tcp有限状态机分析
- [剑指offer]面试题37:两个链表的第一个公共结点
- excel亮灯怎么设置_Excel表格技巧—怎么给表格设置密码
- tomcat 软连接问题
- 准备入行Web前端,又担心适不适合,怎么办?
- 易语言中关于成员变量的声明
- 面试题7:用两个栈实现队列
- win11组策略如何恢复默认设置 windows11组策略恢复默认设置的步骤方法
- Warez出品的精品动画,近25万倍的压缩,大小仅有64K的
- UART协议快速扫盲(图文并茂+超详细)
- 苹果(APPLE)开发人员账号说明及注冊流程(99美元公司版/个人版及299美元企业版)...
- 移远 M26 GSM模组(2G通信模组)AT指令测试 TCP 通信过程
- NR: PointA,offsetToPonitA,kSSB三者关系。
- 游戏支付接口平台如何选择
- 【abaqus demo】6.1平板拉伸-弹塑性分析实例
- 【MMDblender】MMD烘焙后导入blender贴图颜色错乱问题
- Android 动画之一 Drawable Animation —— 逐帧(Frame)动画
热门文章
- ASp.net验证控件RegularExpressionValidator
- java计算机毕业设计药品销售系统源码+数据库+系统+lw文档+mybatis+运行部署
- 狂神说SpringMVC08:拦截器+文件上传下载
- 使用Redis实现登录验证功能
- 两种方式判断有向图是否有环-python实现
- uniapp 录音_uni-app小程序录音上传解决方案(后续更新Taro版)
- 「我的孩子最终没有出生,你们却还在推送育儿广告」
- HCIP之路---vlan实验
- c语言怎么控制输出字符长度,C语言基础之格式化输出控制长度
- 微服务实战之春云与刀客(五)—— spring cloud与docker swarm集群