在线程中抛出异常

4

我尝试使用来自geeksforgeeks的示例1《在Python线程中引发异常》,使用PyThreadState_SetAsyncExc() 来结束运行终止线程的不同方法。 但由于某种原因,线程没有终止。

我使用的是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信号终止吗?

1个回答

5

thread_id 包装在 ctypes.c_long 中,如下:

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

很高兴能够帮助您,欢迎来到 Stack Overflow。如果这个答案或其他任何答案解决了您的问题,请将其标记为已接受。 - alex_noname
2
在Python 3.7中,根据PyThreadState_SetAsyncExc()文档,id参数的类型从long变为unsigned long。 - martineau
谢谢。请问PyThreadState_SetAsyncExc()是什么? - Avv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接