Last active
April 18, 2023 13:59
-
-
Save sajith/f0b856080da0654be6fc364c835fa4f1 to your computer and use it in GitHub Desktop.
What happens when main thread of a Python process crashes?
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
# Adapted from https://realpython.com/intro-to-python-threading/ | |
import logging | |
import threading | |
import time | |
def thread_function(): | |
logging.info("Starting") | |
count = 1 | |
while True: | |
time.sleep(1) | |
logging.info( | |
f"Current thread live?: {threading.current_thread().is_alive()}, " | |
f"Main thread live?: {threading.main_thread().is_alive()}, " | |
f"Count: {count}" | |
) | |
count = count + 1 | |
# Let thread_function crash. | |
if count == 20: | |
logging.info(f"Here I crash: {1/0}") | |
if __name__ == "__main__": | |
format = "%(asctime)s: %(threadName)s: %(message)s" | |
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S") | |
logging.info("Before creating thread") | |
t1 = threading.Thread(target=thread_function) | |
logging.info("Before running thread") | |
t1.start() | |
# Do nothing for some seconds. | |
time.sleep(2) | |
# Main thread raises a ZeroDivisionError here, but the other | |
# thread keeps running. | |
logging.info(f"Here I crash: {1/0}") | |
# This will never get logged because the main thread crashed. | |
logging.info("All done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment