1

I'm using threads in my project I want to subclass threading.Thread and implement the stop method there, so I can subclass this class. look at this -

class MyThread(threading.Thread):
    __metaclass__ = ABCMeta

    def run(self):
        try:
            self.code()
        except MyThread.__StopThreadException:
            print "thread stopped."

    @abstractmethod
    def code(self):
        pass

    def stop(self):
        tid = self.get_id()
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
                                                  ctypes.py_object(MyThread.__StopThreadException))
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)

    class __StopThreadException(Exception):
        """The exception I raise to stop the sniffing"""
        pass

    def get_id(self):
        for tid, tobj in threading._active.items():
            if tobj is self:
                return tid

class SniffThread(MyThread):

    def code(self):
        sniff(prn=self.prn)

    def prn(self, pkt):
        print "got packet"



t = SniffThread()
t.start()
time.sleep(10)
t.stop()

It doesn't work because the StopThreadException is raised in the main thread, and I need to find a way to raise it in the SniffThread. Do you have better way to implement the stop method? I need to do it because I work with blocking functions and I need a way to stop the Thread. I know I can use the lfilter of the sniff function and keep a flag but I don't want to do this. I don't want to do it because it will only work with scapy and I want to make an abstract class that can be inherited with a stop method that will work for any thread, the solution needs to be in the MyThread class.

Edit: I looked here and changed my code.

Community
  • 1
  • 1
oridamari
  • 561
  • 7
  • 12
  • 24
  • possible duplicate of [Is there any way to kill a Thread in Python?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) – jonrsharpe Mar 11 '15 at 13:09
  • I read it and didn't understand how to make my thread raise an exception from outside the thread.. – oridamari Mar 11 '15 at 15:17
  • Given that the accepted answer explicitly covers that, I don't know what to tell you. – jonrsharpe Mar 11 '15 at 15:18
  • Look at the changes I have made – oridamari Mar 11 '15 at 15:38
  • *"tried changing my code.. It doesn't work.. help?"* is **not** an on-topic question. Please read http://stackoverflow.com/help/mcve. It might also be helpful to explain *why* you don't want to use the other methods (e.g. setting a stop flag). – jonrsharpe Mar 11 '15 at 15:44

0 Answers0