Python线程join和setDaemon

枫铃3年前 (2021-09-30)Python215

看一下线程的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># 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 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># 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 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># 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 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># 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同步windows和linux文件

写python脚本的初衷,每次在windows编辑完文件后,想同步到linux上去,只能够登录服务器,...

爬虫基本原理

爬虫基本原理 一、爬虫是什么? 百度百科和维基百科对网络爬虫的定义:简单来说爬虫就是抓取目标网站内容的工具,一般是根据定义的行...

Django 函数和方法的区别

函数和方法的区别 1、函数要手动传self,方法不用传 2、如果是一个函数,用类名去调用,如果是一个方法...

Django 知识补漏单例模式

单例模式:(说白了就是)创建一个类的实例。在 Python 中,我们可以用多种方法来实现单例模式&#x...

Django基础知识MTV

Django简介 Django是使用Python编写的一个开源Web框架。可以用它来快速搭建一个高性能的网站。 Django也是一个MVC框架。但是在Dj...

Python mysql 索引原理与慢查询优化

一 介绍 为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。