4

I tried to get the example 1 Raising exceptions in a python thread using PyThreadState_SetAsyncExc() from geeksforgeeks Different ways to kill a Thread running.

But for some reason the thread does not terminate.

I use python3.6

here is the source-code


# 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() 

Does anybody have an idea why the thread is not terminated with the raise signal?

martineau
  • 119,623
  • 25
  • 170
  • 301
MaxM.
  • 71
  • 4

1 Answers1

5

Wrap thread_id in ctypes.c_long as:

res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id),
 ctypes.py_object(SystemExit))
alex_noname
  • 26,459
  • 5
  • 69
  • 86
  • Happy to help, and welcome to Stack Overflow. If this answer or any other one solved your issue, please mark it as accepted. – alex_noname Dec 01 '20 at 12:08
  • 1
    In Python 3.7 the type of the id parameter changed from long to unsigned long according to `PyThreadState_SetAsyncExc()`'s [documentation](https://docs.python.org/3/c-api/init.html?highlight=pythreadstate_setasyncexc#c.PyThreadState_SetAsyncExc) – martineau May 05 '22 at 08:48
  • Thank you. what is `PyThreadState_SetAsyncExc()` please? – Avv Nov 01 '22 at 16:09