Skip to content

Instantly share code, notes, and snippets.

@ejdecena
Created October 24, 2020 20:08
Show Gist options
  • Save ejdecena/c0432ac35ec6b2a357055ba8e8650cfc to your computer and use it in GitHub Desktop.
Save ejdecena/c0432ac35ec6b2a357055ba8e8650cfc to your computer and use it in GitHub Desktop.
Thread Trace.
#!/usr/bin/env python3
# https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/
import sys
import threading
class ThreadTrace(threading.Thread):
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
def start(self):
self.__run_backup = self.run
self.run = self.__run
threading.Thread.start(self)
def __run(self):
sys.settrace(self.globaltrace)
self.__run_backup()
self.run = self.__run_backup
def globaltrace(self, frame, event, arg):
if event == "call":
return self.localtrace
else:
return None
def localtrace(self, frame, event, arg):
if self.killed:
if event == "line":
raise SystemExit()
return self.localtrace
def kill(self):
self.killed = True
if __name__ == "__main__":
# Testing ...
import time
def func():
while True:
print("thread running")
t1 = ThreadTrace(target = func)
t1.start()
time.sleep(2)
t1.kill()
t1.join()
if not t1.isAlive():
print("thread killed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment