Python线程join和setDaemon
看一下线程的setDaemon()方法
import time
import threading
import ctypes
import inspectdef 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
我们修改一下代码:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import time
import threading
import ctypes
import inspectdef 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()方法:
直接看代码
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import time
import threading
import ctypes
import inspectdef 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
修改代码:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import time
import threading
import ctypes
import inspectdef 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 多线程 setdaemon_Python线程join和setDaemon
看一下线程的setDaemon()方法 importtimeimportthreadingimportctypesimportinspectdefsayHello():for i in range(1 ...
- python线程join方法_Python多线程join()用法
Python多线程与多进程中join()方法的效果是相同的. 下面仅以多线程为例: 首先需要明确几个概念: 知识点一:主进程结束,子进程继续执行 当一个进程启动之后,会默认产生一个主线程,因为线程是程 ...
- python线程join方法
前言: join方法的作用是同步线程. 1.不使用join方法: 当设置多个线程时,在一般情况下(无守护线程,setDeamon=False),多个线程同时启动,主线程执行完,会等待其他子线程执行完, ...
- Python中threading的join和setDaemon的区别及用法 例子
Python中threading的join和setDaemon的区别及用法 Python多线程编程时,经常会用到join()和setDaemon()方法,今天特地研究了一下两者的区别. 1.join ...
- Python教程:threading中join与setDaemon的用法及区别讲解
Python多线程编程时经常会用到join()和setDaemon()方法,基本用法如下: join([time]): 等待至线程中止.这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或 ...
- Python中threading的join和setDaemon的区别及用法
Python多线程编程时经常会用到join()和setDaemon()方法,基本用法如下: join([time]): 等待至线程中止.这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或 ...
- python中thread的setDaemon、join的用法
From: http://doudouclever.blog.163.com/blog/static/17511231020127232303469/ python中得thread的一些机制和C/C+ ...
- python等待线程结束_python线程join
几个事实 1 python 默认参数创建线程后,不管主线程是否执行完毕,都会等待子线程执行完毕才一起退出,有无join结果一样 2 如果创建线程,并且设置了daemon为true,即thread.se ...
最新文章
- 谈谈基于OAuth 2.0的第三方认证 [上篇]
- Voice LAB-1 CUBE Cisco Unified Border Element
- 计算同比 环比_PowerBI学习教程(三)时间累积同比环比计算
- 111. Minimum Depth of Binary Tree 二叉树的最小深度
- php扩展管理配置信息,PHP扩展管理 - 城市之雾的个人空间 - OSCHINA - 中文开源技术交流社区...
- java怎吗从磁盘读文件_编写一个Java应用程序,该程序使用FileInputStream类,实现从磁盘读取本应用程序源代码文件,并将文件内容显示在屏幕上。...
- java编程方向_java网络编程方向具体该怎么去学
- centos 5.6 安装redmine 步骤
- mysql 5.6 二进制安装包_centos6上mysql5.6二进制包安装
- DateTable复制表行
- .Net Remoting 入门
- python无穷大怎么表示_python如何表示无穷大
- java实现psd格式图片读入
- Vue父组件传参数给子组件时,页面崩溃或者报undefined或者数据为空或者执行了两遍
- Python Selenium破解滑块验证码最新版!
- Android名片识别
- 能力开放平台系列-概述
- mc服务器常用指令_mc服务器新手指令
- 两个决策树例题经典案例-代码示例
- RTOS与Linux