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 ...
随机推荐
- 简单认识RTLO(Right-to-Left Override)
目录 两行代码实现字符逆序输出 做个假文件 参考 今天在群里看到的用法,RLO是一个微软的中东Unicode字符8238,或者0x202E,可以使后面的字符都变为RTL(阿拉伯语从右往左书写,对我们来 ...
- java对象转变为map
直接上代码 package com.**.**.**.common; import com.**.**.**.util.JsonUtils; import org.springframework.be ...
- SVN与GIT工具使用对比
版本工具 差异 svn git 系统特点 1.集中式版本控制系统(文档管理很方便) 2.企业内部并行集中开发 3.windows系统上开发推荐使用 4.克隆一个拥有将近一万个提交(commit),五个 ...
- 第十二节:Asp.Net Core 之分布式缓存(SQLServer和Redis)
一. 整体说明 1. 说明 分布式缓存通常是指在多个应用程序服务器的架构下,作为他们共享的外部服务共享缓存,常用的有SQLServer.Redis.NCache. 特别说明一下:这里的分布式是 ...
- Java学习:线程间通信
线程间通信 概念:多个线程在处理同一个资源,但是处理的动作(线程的任务)却不相同重点:有效的利用资源 分析:需要那些类 1 资源类:包子类 设置包子的属性 包子的状态:有true 没有false 2 ...
- PowerBI开发 第四篇:DAX 表达式基础
DAX 表达式主要用于创建度量列(Measure),度量值是根据用户选择的Filter和公式,计算聚合值,DAX表达式基本上都是引用对应的函数,函数的执行有表级(Table-Level)上下文和行级( ...
- php for循环a到z
首先先介绍2个php内置函数 ord(string):函数返回字符串的首个字符的 ASCII 值.//string:必需.要从中获得 ASCII 值的字符串. chr(ascll): 函数从指定的 A ...
- Eclipse集成Git做团队开发:代码管理
在日常开发工作中,我们通常使用版本控制软件管理团队的源代码,常用的SVN.Git.与SVN相比,Git有分支的概念,可以从主分支创建开发分支,在开发分支测试没有问题之后,再合并到主分支上去,从而避免了 ...
- Java之路---Day19(set接口)
set接口 java.util.Set 接口和 java.util.List 接口一样,同样继承自 Collection 接口,它与 Collection 接口中的方 法基本一致,但是set接口中元素 ...
- 28、IE报vuex requires a Promise polyfill in this browser问题解决
解决方法第一步: 安装 babel-polyfill . babel-polyfill可以模拟ES6使用的环境,可以使用ES6的所有新方法 npm install --save babel-polyf ...