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())  # 查看线程运行状态
    

    多种方法实现

  • 相关阅读:
    IOS之UIKit_Day13
    IOS之UIKit_Day12
    IOS之UIKit_Day11
    IOS之UIKit_Day10
    iOS设计模式之工厂模式
    常用操作
    盒子模式
    block循环使用问题
    IOS-sqlite3
    IOS-View用作控制器
  • 原文地址:https://www.cnblogs.com/songhaixing/p/15607208.html
Copyright © 2011-2022 走看看