python 多线程终止

本文介绍了如何在Python中创建自定义线程类`thread_with_exception`,它允许正确处理任务函数执行完毕后的回调和异常情况,以及如何使用异步方式强制结束线程。作者还展示了如何在主线程控制子线程的生命周期和异常处理。
摘要由CSDN通过智能技术生成

        最早应该是stackoverflow上面的,在b站看到up主匿名者已逝的代码,觉得有意思,故复制下来研究研究。

import threading
import ctypes
import warnings
import time

class thread_with_exception(threading.Thread):
    def __init__(self,task_function,callback_function=None):
        threading.Thread.__init__(self)
        self.task_function=task_function
        self.callback_function=callback_function
        self.stop=False
    def run(self):
        if not callable(self.task_function):
            raise ValueError("callback_function parameter must be a function!")
        # target function or thread class
        try:
            self.task_function()
        finally:
            if self.stop:
                """
                这里应当做资源释放,减少强制杀死线程的影响
                """
                print("线程被强制结束")
                self.callback_function()
            pass
    def get_id(self):

        # 各自线程返回的id
        # returns id of the respective thread
        if hasattr(self,'_thread_id'): # attribute 属性
            return self._thread_id
        for id,thread in threading._active.items():
            if thread is self:
                return id
    def raise_exception(self):

        #只有存活的线程才有必要强制结束
        if not self.is_alive():
            warnings.warn("no need to stop dead thread!")
            return
        thread_id=self.get_id()
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,ctypes.py_object(SystemExit))
        if res==0:
            warnings.warn("Invalid thread id!")
        elif res>1:
            ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,0)
            warnings.warn("Exception raise failure")
            return
        self.stop=True

if __name__ == "__main__":
    from threading import Condition, Lock, RLock
    from threading import Event
    import _thread
    self_condition=Condition()
    nlock=_thread.allocate_lock()
    # self_condition=RLock()
    # clock = Lock()
    # eflag = Event()

    def user_task_func():
        while True:
            print("准备执行...")
            self_condition.acquire()
            self_condition.wait() # 想办法跳过wait阻塞函数
            print("开始执行任务")
            time.sleep(10.5)
            nlock.acquire()
            print("逻辑2执行完毕")
            nlock.release()
            print("执行用户任务结束")
            self_condition.notify()
            self_condition.release()

    def release():
        try:
            self_condition.release()
            nlock.release()
        except Exception:
            pass
        print("结束子线程")
    t1=thread_with_exception(user_task_func,release)
    # t1.setDaemon(False) 默认是false,
    # 如果某个子线程的daemon属性为False,主线程结束时会检测该子线程是否结束,如果该子线程还在运行,则主线程会等待它完成后再退出;
    t1.start()
    time.sleep(0.5)
    # 注意以下三行,有无懂哥解释一下
    self_condition.acquire()
    self_condition.notify()
    self_condition.release()

    while True:
        command=input()
        if command=="kill":
            t1.raise_exception()
        if command=="exit":
            break

    print("检测子进程存活状态",t1.is_alive())
    # print("检测子进程持有锁状态",self_condition)
    print("主线程结束")


        下面这个是51我心依旧大佬的博客。

import threading
import time
import inspect
import ctypes


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)


def print_time(e):
    while 2:
        print(e)




if __name__ == "__main__":
    t = threading.Thread(target=print_time,args=("2"))
    t.start()
    time.sleep(0.001)
    stop_thread(t)
    print("stoped")
    time.sleep(2)
    t1 = threading.Thread(target=print_time,args=("1"))
    t1.start()
    time.sleep(0.001)
    stop_thread(t1)
    print("stoped")
    while 1:
        pass

参考链接

【这个可能是B站第一个讲python多线程正确终止的视频,有BUG分析】

python 线程如何关闭 python thread关闭线程_我心依旧的技术博客_51CTO博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,如果你想要终止一个正在运行的线程,你可以通过`Thread`对象的`terminate()`、`join()`或`cancel()`方法来实现。以下是几种常见的方法: 1. **terminate()**: 这个方法会发送一个SIGTERM信号给线程,请求其停止。如果线程还没有处理这个信号,它会在一定时间后强制退出。例如: ```python import threading def target_function(): # 线程代码... thread = threading.Thread(target=target_function) # ...启动线程... # 要终止线程 if thread.is_alive(): # 检查线程是否还在运行 thread.terminate() ``` 请注意,这并不是一种优雅的方式来结束线程,因为可能会导致数据未保存等异常。 2. **join()**: 使用`join()`方法可以等待线程执行完毕再继续。如果设定了超时时间,可以通过`thread.join(timeout)`来在指定秒数内等待线程结束。如果超时,线程不会被终止,而是返回到主线程。 ```python thread.join() # 如果设置timeout参数,如thread.join(5),那么最多等待5秒 ``` 3. **cancel()**: 在Windows平台上,你可以使用`Event`对象配合`ThreadPoolExecutor`来取消任务,但它不是所有平台通用的。例如: ```python from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(target_function) if not future.cancelled(): # 取消任务前检查是否已被取消 future.cancel() ``` 在Python标准库中,`cancel()`方法对于非守护线程效果有限,因为守护线程默认会被系统清理掉,而不必手动取消。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值