zoukankan      html  css  js  c++  java
  • ✍45 使用ctypes终止线程

    from threading import Thread
    import time
    import inspect
    import ctypes
    
    
    def _async_raise(tid, exctype):
        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):
        thread._is_stopped = True  # 修改线程状态
        _async_raise(thread.ident, SystemExit)
    
    
    def task():
        for i in range(1, 100):
            print(i)
            time.sleep(1)
    
    
    if __name__ == '__main__':
        th = Thread(target=task)
        th.start()  # 开始线程
        print(th.is_alive())  # 查看线程运行状态
        time.sleep(2)
        stop_thread(th)  # 终止线程
        print(th.is_alive())  # 查看线程运行状态
    

    多种方法实现

  • 相关阅读:
    电视剧的拍摄和发行
    常用键盘快捷键
    河北省各城市名称由来
    爱情16谈
    人生赏心十六件乐事
    Android——apk反编译
    Android.mk
    Android——init可执行程序
    Android启动脚本init.rc(2)
    MountService初探
  • 原文地址:https://www.cnblogs.com/songhaixing/p/15607208.html
Copyright © 2011-2022 走看看