Created
September 15, 2016 08:11
-
-
Save sirkonst/5bfd26f7f07c692441be76dc6c973cb4 to your computer and use it in GitHub Desktop.
Kill thread in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
import threading | |
import time | |
# inspired by https://github.com/mosquito/crew/blob/master/crew/worker/thread.py | |
def kill_thread( | |
thread: threading.Thread, exception: BaseException=KeyboardInterrupt | |
) -> None: | |
if not thread.isAlive(): | |
return | |
res = ctypes.pythonapi.PyThreadState_SetAsyncExc( | |
ctypes.c_long(thread.ident), ctypes.py_object(exception) | |
) | |
if res == 0: | |
raise ValueError('nonexistent thread id') | |
elif res > 1: | |
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) | |
raise SystemError('PyThreadState_SetAsyncExc failed') | |
while thread.isAlive(): | |
time.sleep(0.01) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment