thread_stopper.py
Go to the documentation of this file.
00001 import threading
00002 import inspect
00003 import ctypes
00004 import time
00005  
00006  
00007 def _async_raise(tid, exctype):
00008     """raises the exception, performs cleanup if needed"""
00009     if not inspect.isclass(exctype):
00010         raise TypeError("Only types can be raised (not instances)")
00011     res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
00012     if res == 0:
00013         raise ValueError("invalid thread id")
00014     elif res != 1:
00015         # """if it returns a number greater than one, you're in trouble, 
00016         # and you should call it again with exc=NULL to revert the effect"""
00017         ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
00018         raise SystemError("PyThreadState_SetAsyncExc failed")
00019  
00020  
00021 class Thread(threading.Thread):
00022     def _get_my_tid(self):
00023         """determines this (self's) thread id"""
00024         if not self.isAlive():
00025             raise threading.ThreadError("the thread is not active")
00026  
00027         # do we have it cached?
00028         if hasattr(self, "_thread_id"):
00029             return self._thread_id
00030  
00031         # no, look for it in the _active dict
00032         for tid, tobj in threading._active.items():
00033             if tobj is self:
00034                 self._thread_id = tid
00035                 return tid
00036  
00037         raise AssertionError("could not determine the thread's id")
00038  
00039     def raise_exc(self, exctype):
00040         """raises the given exception type in the context of this thread"""
00041         _async_raise(self._get_my_tid(), exctype)
00042  
00043     def terminate(self):
00044         """raises SystemExit in the context of the given thread, which should 
00045         cause the thread to exit silently (unless caught)"""
00046         self.raise_exc(SystemExit)
00047 
00048 def f():
00049     try:
00050         while True:
00051             time.sleep(0.1)
00052     finally:
00053         print "outta here"
00054 
00055 
00056 if __name__ == '__main__':
00057     t = Thread(target = f)
00058     t.start()
00059     print 'is alive', t.isAlive()
00060     time.sleep(1)
00061     print 'terminating'
00062     t.terminate()
00063     print 'is alive', t.isAlive()
00064     print 'join'
00065     t.join()
00066     print 'is alive', t.isAlive()


rcommander
Author(s): Hai Nguyen (haidai@gmail.com)
autogenerated on Thu Nov 28 2013 11:46:34