美文网首页
python 强制停止线程

python 强制停止线程

作者: yichen_china | 来源:发表于2021-02-03 14:48 被阅读0次

2020-12-13更新:
ctypes终止线程:

# coding=utf-8
import threading
import time
import ctypes
import inspect
import asyncio


def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    try:
        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:
            # pass
            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")
    except Exception as err:
        print(err)


def stop_thread(thread):
    """终止线程"""
    _async_raise(thread.ident, SystemExit)


class CountdownTask:
    def run(self, n):
        while True:
            # 将要执行的任务放在此处
            # 示例
            print("T-minus  {}\n".format(n))
            n -= 1
            asyncio.sleep(100)
            # time.sleep(100)
            # end


# 示例
# stop threading
countdownTask = CountdownTask()
th = threading.Thread(target=countdownTask.run, args=(10,))  # args可以给run传参
th.start()
time.sleep(2)
stop_thread(th)  # Signal termination
# end

原文

# coding=utf-8
import threading
import time


class CountdownTask:
    def __init__(self):
        self._running = True

    def terminate(self):
        self._running = False

    def run(self, n):
        while self._running:
            # 将要执行的任务放在此处
            # 示例
            print("T-minus  {}\n".format(n))
            n -= 1
            time.sleep(100)
            # end


# 示例
# stop threading
countdownTask = CountdownTask()
th = threading.Thread(target=countdownTask.run, args=(10,))  # args可以给run传参
th.start()
countdownTask.terminate()  # Signal termination
# end

相关文章

  • python 强制停止线程

    2020-12-13更新:ctypes终止线程: 原文

  • Java中如何正确停止线程?两种停止线程最佳方法

    如何正确停止线程 使用 interrupt 来通知,而不是强制 1:普通情况停止线程 通知停止线程thread.i...

  • 线程状态

    线程的5个状态 目录 线程停止 线程休眠 线程礼让(不重要) 线程强制执行 线程状态观测 1. 线程停止 Warn...

  • 线程交互

    (1)在线程中停止另一个线程 thread.stop(); 强制停止 (不安全) 由于stop的时候线程可能处于...

  • Thread.interrupt()的理解

    目标 一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。Thread.interrupt 的作...

  • Java线程中断

    首先,一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。所以,Thread.stop, Thr...

  • Interrupt 线程与OS

    基本思想 一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。 中断,只是一个协作通知信号量。好...

  • 第五章如何正确停止线程

    一、原理介绍:使用Interrupt来通知停止线程,而不是强制。在什么情况下会需要用到停止线程?或许是用户主动取消...

  • python 多线程 锁

    参考:《Python cookbook》12章 启动和停止线程 start 启动线程; is_alive 判断是否...

  • Python强制杀死线程

网友评论

      本文标题:python 强制停止线程

      本文链接:https://www.haomeiwen.com/subject/tjtezktx.html