• 技术文章 >Python技术 >Python基础教程

    python线程强制停止工作

    十一十一2020-12-31 15:24:24原创2852


    线程模块没有停止方法,是为了安全,但是我们需要停止子线程呢。小编罗列了,可以有几种安全停止线程的方式,主要涉及的是需要将共享变量作为标志、event对象还有调用C函数接口,但是如果碰到需要去强制停止线程的方式,这就需要我们去调用C函数接口,一起来了解下吧。

    强制停止线程,ctypes 调用 C 函数接口

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    import threading

    import time

    import inspect

    import ctypes

    def _async_raise(tid, exctype):

        if not inspect.isclass(exctype): 

            exctype = type(exctype)

        elif res != 1:

            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)

            raise SystemError("PyThreadState_SetAsyncExc failed")

    def stop_thread(thread):

    如果大家想看安全停止的方式,需要去判断标识,退出线程,另外强制停止线程是需要我们ctypes 调用C语言的内部函数,强制退出线程,以上都是基于主线程停止子线程的情况哦~

    专题推荐:python线程
    上一篇:python condition条件变量 下一篇:Python里SimpleQueue和LifoQueue的用法

    相关文章推荐

    • python condition条件变量

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网