看一下线程的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的更多相关文章

  1. python线程join

    几个事实 1 python 默认参数创建线程后,不管主线程是否执行完毕,都会等待子线程执行完毕才一起退出,有无join结果一样 2 如果创建线程,并且设置了daemon为true,即thread.se ...

  2. Python多线程join和setDaemon区别与用法

    一直没有太搞清楚join和setDaemon有什么区别,总是对于它们两个的概念很模糊,需要做个实验然后记录一下. 先说结论: join: 子线程合并到主线程上来的作用,就是当主线程中有子线程join的 ...

  3. python线程join方法

    转载:http://www.cnblogs.com/cnkai/p/7504980.html Python多线程与多进程中join()方法的效果是相同的. 下面仅以多线程为例: 首先需要明确几个概念: ...

  4. python的threading.Thread线程的start、run、join、setDaemon

    Pycharm整体看下Thread类的内容:模拟的是Java的线程模型 表示方法method,上面的锁头表示这个是类内部的方法,从方法名字命名规范可以看出,都是_和__开头的,一个下划线表示是子类可以 ...

  5. 关于python多线程编程中join()和setDaemon()的一点儿探究

    关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的  ...

  6. Python中threading的join和setDaemon的区别及用法

    Python多线程编程时经常会用到join()和setDaemon()方法,基本用法如下: join([time]): 等待至线程中止.这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或 ...

  7. python网络编程--线程join和Daemon(守护进程)

    一:什么情况下使用join join([timeout])调用join函数会使得主调线程阻塞,直到被调用线程运行结束或超时. 参数timeout是一个数值类型,用来表示超时时间,如果未提供该参数,那么 ...

  8. Python中threading的join和setDaemon的区别及用法[例子]

    Python多线程编程时,经常会用到join()和setDaemon()方法,今天特地研究了一下两者的区别. 1.join ()方法:主线程A中,创建了子线程B,并且在主线程A中调用了B.join() ...

  9. Python中threading的join和setDaemon的区别[带例子]

    python的进程和线程经常用到,之前一直不明白threading的join和setDaemon的区别和用法,今天特地研究了一下.multiprocessing中也有这两个方法,同样适用,这里以thr ...

随机推荐

  1. 关于“100g文件全是数组,取最大的100个数”解决方法汇总

    原题如下: 有一个100G大小的文件里存的全是数字,并且每个数字见用逗号隔开.现在在这一大堆数字中找出100个最大的数出来. 我认为,首先要摸清考官的意图.是想问你os方面的知识,还是算法,或者数据结 ...

  2. Django学习----js传参给view.py

    需求: 散点图中每选择一个点,获取到id之后传给view.py,根据这个id进行sql语句的查询. 问题: 要求实时查询 解决办法: ajax查询 js页面 .on("mousedown&q ...

  3. Java基础之十三 字符串

    第十三章 字符串 13.1 不可变String String对象是不可变的.String类中每一个看起来会修改String值得方法,实际上都是创建了一个全新得String对象,以包含修改后得字符串内容 ...

  4. HashTable源码

    1. 为什么无法创建更大的数组? Attempts to allocate larger arrays may result in OutOfMemoryError 如果数组长度过大,可能出现的两种错 ...

  5. Zookeeper connection loss leads to Flink job restart

    Flink可以使用zookeeper来进行ha,而一般我们都会使用zookeeper的高级api架构curator来对zk进行通讯.在curator中引入了状态的概念,包括connected,reco ...

  6. SQLServer --------- 将sql脚本文件导入数据库

    创建数据库方法有两种 第一种通过图形化的操作界面 第二种通过 sql 语句 sql server 如何执行.sql 文件,的原理就是执行sql语句进行创建 打开数据库后找到   最左侧文件 找到需要执 ...

  7. [转帖]B4. Concurrent JVM 锁机制(synchronized)

    B4. Concurrent JVM 锁机制(synchronized) https://www.cnblogs.com/zlxyt/p/11050346.html 挺好的 感觉这个文章写的 不过想要 ...

  8. python模块、异常

    1. python 模块 模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py.模块可以被别的程序引入,以使用该模块中的函数等功能.这也是使用 python 标准库的方法.(有点像java的c ...

  9. 快速获取更丰富的Sitecore体验数据库

    无论您是否立即使用Sitecore的营销功能,我们强烈建议您执行这三项任务,以使您的数据收集更加丰富,并为您以后的决策留下良好的位置. Sitecore的体验数据库,即xDB,是Sitecore营销平 ...

  10. 如何用Python制作优美且功能强大的数据可视化图像

    第一个案例 首先开始来绘制你的第一个图表 from pyecharts import Bar '''遇到不懂的问题?Python学习交流群:1004391443满足你的需求,资料都已经上传群文件,可以 ...