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 ...
随机推荐
- Windows远程桌面连接Debian
参考 https://portal.databasemart.com/kb/a457/how-to-install-desktop-environment-and-xrdp-service-in-de ...
- k8s 相关的命令
查看node信息 kubectl describe node k8s-node- 查看dashboard token kubectl describe pod kubernetes-dashboard ...
- c# 创建socket连接辅助类
using AD.SocketForm.Model; using NLog; using System; using System.Net; using System.Net.Sockets; nam ...
- [C++基础] 数组、指针、内存篇
一.数组 2.1 int a[2][2]= { {1}, {2,3} },则 a[0][1] 的值是多少? 二维数组的初始化一般有两种方式: 第一种方式是按行来执行,如int array\[2][3] ...
- 【原创】在windows下使用xampp搭建phpcms v9
我的操作环境: 操作系统:windows 7 64 位操作系统(有点古老,哈哈) 1.下载php环境和phpcmsv9源代码:phpcms v9 的源码:phpcms_v9.5.10_UT ...
- JSON ------ 创建与访问
JSON (Java Script Object Notation, js对象表示法) 是存储和交换文本信息的语法,类似 XML JSON的文件类型是 “.json” 优点: 比XML ...
- 【题解】Luogu P5468 [NOI2019]回家路线
原题传送门 前置芝士:斜率优化 不会的可以去杜神博客学 这道题我考场上只会拆点跑最短路的70pts做法 后来回家后发现错误的爆搜都能拿满分(刀片) 还有很多人\(O(mt)\)过的,还是要坚持写正解好 ...
- Java学习:面向对象三大特征:封装性、继承性、多态性之多态性。
面向对象三大特征:封装性.继承性.多态性之多态性. extends继承或者implemens实现,是多态性的前提. 例如:小菜是一个学生,但同时也是一个人.小菜是一个对象,这个对象既有学生形态,也有人 ...
- docker镜像上传阿里云仓库
推送至阿里云镜像:1.首先在阿里云上选择容器镜像服务,创建命名空间以及镜像仓库2. docker login --username=zhangshitongsky@163.com registry.c ...
- SSRS连接ORACLE数据库制作报表
SSRS报表基于ORACLE数据库做报表示例. 开发环境:VS2010 SQL SERVER 数据库:SQL SERVER 2012 PS:数据库连接部分可能有还有个问题就是ORACLE数据源这一部分 ...