首页 > 编程语言 >Python终止线程的方法

Python终止线程的方法

时间:2023-04-13 09:55:21浏览次数:28  
标签:raise thread exctype Python tid 线程 终止 ctypes

亲测使用如下方法有效,但是如果线程中涉及获取释放锁,可能会导致死锁。


def _async_raise(tid, exctype):
    """
    线程退出,这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。
    :param tid: thread id
    :param exctype: https://docs.python.org/zh-cn/3.8/library/exceptions.html
    :return: None
    """
    """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):
    """
    线程退出封装方法
    :param thread: 线程对象
    :return: None
    """
    _async_raise(thread.ident, SystemExit)

完整示例代码如下:

import time
import ctypes
import inspect
import threading


def _async_raise(tid, exctype):
    """
    线程退出,这种方法是强制杀死线程,但是如果线程中涉及获取释放锁,可能会导致死锁。
    :param tid: thread id
    :param exctype: https://docs.python.org/zh-cn/3.8/library/exceptions.html
    :return: None
    """
    """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):
    """
    线程退出封装方法
    :param thread: 线程对象
    :return: None
    """
    _async_raise(thread.ident, SystemExit)


def run():
    while True:
        print(f"thread id = {threading.current_thread().ident}")
        time.sleep(1)


TaskThread = threading.Thread(target=run)
TaskThread.setDaemon(True)
TaskThread.start()

while True:
    time.sleep(3)
    stop_thread(TaskThread)
    TaskThread = threading.Thread(target=run)
    TaskThread.setDaemon(True)
    TaskThread.start()

运行结果如下图所示
image

标签:raise,thread,exctype,Python,tid,线程,终止,ctypes
From: https://www.cnblogs.com/liuyangQAQ/p/17312299.html

相关文章

  • Python timezone package All In One
    PythontimezonepackageAllInOne中文日期格式化Asia/Shanghai#!/usr/bin/envpython3#coding:utf8importtimefromdatetimeimportdatetime,tzinfo,timezone#importpytz#❌ModuleNotFoundError:Nomodulenamed'pytz'#pip3installpytz#......
  • 使用shell,python,go来实现ansible的自定义模块
    一、自定义模块运行原理二、自定义模块实战2.1shell方式2.2python方式2.3golang方式三、测试验证3.1shell方式验证3.2python方式验证3.3golang方式验证ansible已经提供了非常多的模块,涵盖了系统、网络、数据库、容器、以及其他的方方面面的领域,几乎可以不用重复......
  • spring事务里面开启线程插入,报错了是否会回滚?
    1.前言一道非常有意思的面试题目。大概是这样子的,如果在一个事务中,开启线程进行插入更新等操作,如果报错了,事务是否会进行回滚2.代码示例1@RequestMapping("/test/publish/submit")publicStringtestPublish1(){ log.info("start..."); transactionTemplate.execute(new......
  • 今日总结-python连接数据库的学习
          ......
  • 3-面试题(python)
    1、列表和字典的区别字典是{}表示的,列表是[]表示的;字典是无序的不能通过索引来取值,列表是有序的;字典是以键值对的形式存在的,列表相当于一个容器,里面可以放置任何的数据类型; 2、python中的数据类型string、number、tuple、list、dictionary、set;3、python怎么将一个对象转......
  • 多线程应用案例
    需求解析一个Excel中多个sheet的数据,那么此时就可以考虑使用多线程,每个线程解析一个sheet中的数据,然后等待所有的sheet数据解析完成后,再把数据入库在这个需求中,要实现主线程等待所有现场完成shee数据解析操作,第一种方案:采用join()方法publicclassMyJoinTest{publicstaticvoid......
  • 【NLP开发】Python实现聊天机器人(OpenAI,开发指南笔记)
    1、开始使用1.1介绍OpenAIAPI几乎可以应用于任何涉及理解或生成自然语言或代码的任务。我们提供一系列具有不同功率水平的型号,适用于不同的任务,并能够微调您自己的定制模型。这些模型可用于从内容生成到语义搜索和分类的所有内容。提示和完成(Promptsandcompletions)compl......
  • 【视频】随机波动率SV模型原理和Python对标普SP500股票指数预测|数据分享|附代码数据
    全文链接:http://tecdat.cn/?p=22546最近我们被客户要求撰写关于随机波动率SV模型的研究报告,包括一些图形和统计输出。什么是随机波动率?随机波动率(SV)是指资产价格的波动率是变化的而不是恒定的。 “随机”一词意味着某些变量是随机确定的,无法精确预测。在金融建模的背景......
  • 2-面试题:python
    1、python对象的比较和拷贝?答:'=='操作符比较对象之间的值是否相等;'is'操作符比较的是对象的身份标识是否相等,即它们是否是同一个对象,是否指向同一个内存地址;比较操作符'is'的速度效率,通常优于'==';浅拷贝和深拷贝:浅拷贝,将原对象或原数组的引用直接赋值给新对象、新数组,新对象/......
  • threading多线程使用
    当我们调用某段代码时需要等待一段时间后才能进行后续的操作,而这期间计算资源并未占满,这就浪费了CPU的资源和时间,此时可以采用多线程进行并行计算。如当我们使用爬虫爬取网络资源时,某个资源的爬取过程由于网络因素需要等待,而后续的资源清洗和整合等需要等待,此时可以将资源分多份......