add killthread function, make Task killable; Task daemonizes per default
This commit is contained in:
23
modman/killthread.py
Normal file
23
modman/killthread.py
Normal file
@ -0,0 +1,23 @@
|
||||
import ctypes
|
||||
|
||||
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
|
||||
|
||||
|
||||
def killthread(thread, exc=KeyboardInterrupt):
|
||||
if not thread.is_alive():
|
||||
return
|
||||
|
||||
ident = ctypes.c_long(thread.ident)
|
||||
exc = ctypes.py_object(exc)
|
||||
|
||||
res = set_async_exc(ident, exc)
|
||||
if res == 0:
|
||||
raise ValueError("thread id does not exist")
|
||||
elif res > 1:
|
||||
# if return value is greater than one, you are in trouble.
|
||||
# you should call it again with exc=NULL to revert the effect.
|
||||
set_async_exc(ident, None)
|
||||
raise SystemError("PyThreadState_SetAsyncExc failed")
|
||||
|
||||
|
||||
|
@ -1,14 +1,19 @@
|
||||
from threading import Thread
|
||||
|
||||
from killthread import killthread
|
||||
|
||||
|
||||
class Task(Thread):
|
||||
|
||||
def __init__(self, target, name, **kwargs):
|
||||
super().__init__(group=None, target=target, name=name, **kwargs)
|
||||
def __init__(self, target, name, daemon=True, **kwargs):
|
||||
super().__init__(group=None, target=target, name=name, daemon=daemon, **kwargs)
|
||||
|
||||
@property
|
||||
def is_running(self):
|
||||
return self.is_alive()
|
||||
|
||||
def kill(self):
|
||||
killthread(self)
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user