Skip to content

Instantly share code, notes, and snippets.

@nevmerzhitsky
Last active March 23, 2019 16:41
Show Gist options
  • Save nevmerzhitsky/492abc28466b31ba890f19b9cab69dd8 to your computer and use it in GitHub Desktop.
Save nevmerzhitsky/492abc28466b31ba890f19b9cab69dd8 to your computer and use it in GitHub Desktop.
Python - Terminate main thread from a child
import os
import signal
import threading
import time
def install_thread_exceptions_hook():
old_run = threading.Thread.run
def run(*args, **kwargs):
try:
old_run(*args, **kwargs)
except Exception:
os.kill(os.getpid(), signal.SIGUSR1)
raise
threading.Thread.run = run
class ExitCommand(Exception):
pass
def signal_handler(signal, frame):
raise ExitCommand()
def thread_job():
for i in range(10):
time.sleep(1)
print(f'Child thread: {i}')
if i == 2:
raise RuntimeError('Exception in a child thread!')
def main():
install_thread_exceptions_hook()
signal.signal(signal.SIGUSR1, signal_handler)
thread = threading.Thread(target=thread_job)
thread.start()
for t in range(20):
time.sleep(1)
print(f'Main thread: {t}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment