Search code examples
pythonpython-3.xassertpython-multithreading

Python3: Kill main thread when assert on another thread


Please see this code:

#! /usr/bin/env python3

import threading
import time


def asserter():
    time.sleep(3)
    assert False


threading.Thread(target=asserter).start()

while True:
    print('Main')
    time.sleep(1)

I need the main loop to die when the assertion is launched. How should it be done?


Solution

  • You'd need to catch any threaded exceptions in the thread itself. You can then communicate that result back to the main thread somehow. Here's a minimal example that uses a shared flag object to indicate that thread has crashed. The main loop can then simply wait for that flag to change.

    import threading
    import time
    
    class Flag:
        ended = False
    
    def asserter(flag):
        time.sleep(3)
        try:
            assert False
        except AssertionError:
            flag.ended = True
    
    
    thread = threading.Thread(target=asserter, args=(Flag,))
    thread.start()
    
    while not Flag.ended:
        print('Main')
        time.sleep(1)
    print('done')