在线程中引发异常

Raising exceptions in a thread

我尝试获取示例 1 使用 geeksforgeeks 的 PyThreadState_SetAsyncExc() 在 python 线程 中引发异常 Different ways to kill a Thread 运行.

但由于某种原因线程没有终止。

我用python3.6

这是源代码


# Python program raising 
# exceptions in a python 
# thread 
  
import threading 
import ctypes 
import time 
   
class thread_with_exception(threading.Thread): 
    def __init__(self, name): 
        threading.Thread.__init__(self) 
        self.name = name 
              
    def run(self): 
  
        # target function of the thread class 
        try: 
            while True: 
                print('running ' + self.name) 
        finally: 
            print('ended') 
           
    def get_id(self): 
  
        # returns id of the respective thread 
        if hasattr(self, '_thread_id'): 
            return self._thread_id 
        for id, thread in threading._active.items(): 
            if thread is self: 
                return id
   
    def raise_exception(self): 
        thread_id = self.get_id() 
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 
              ctypes.py_object(SystemExit)) 
        if res > 1: 
            ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 
            print('Exception raise failure') 
       
t1 = thread_with_exception('Thread 1') 
t1.start() 
time.sleep(2) 
t1.raise_exception() 
t1.join() 

有人知道为什么线程没有被 raise 信号终止吗?

thread_id 换成 ctypes.c_long 为:

res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id),
 ctypes.py_object(SystemExit))