I’m struggling to understand what happens to other threads when ctrl+c interrupts the main thread while it’s waiting for the other thread to finish.
Here’s a small snippet of code to illustrate an example.
import time, threading
def worker():
time.sleep(5)
print("Thread finished")
t = threading.Thread(target=worker)
t.start()
try:
t.join()
except KeyboardInterrupt:
print("Interrupted")
With this code, if I hit ctrl+c before the 5s are up, I expect the main thread to have a KeyboardInterrupt raised within the join
, then it would get caught by the except
block, printing “Interrupted”.
Then the main thread would reach the end of its code and exit, but python should not shut down yet until the thread completes, since it’s not a daemon thread. The thread should then print “Thread finished”, and only then the python process should exit.
This is in line with my observations using python 3.6 and 3.7, however when I try this with python 3.11 and 3.12, it prints “Interrupted” and the process immediately exits.
What seems even stranger to me is that if I replace the t.join()
with a time.sleep(100000)
then it does wait for the thread to finish before exiting… It seems as if the thread is being abruptly aborted if the ctrl+c happens during the join
, but not otherwise…
I couldn’t find any explanation for this in the docs. The only relevant information I found was this, which seems to me like 3.11 and 3.12 are misbehaving.
The entire Python program exits when no alive non-daemon threads are left.
Is this actually just a bug or is there a real explanation that I don’t know as to why it behaves this way? If so, is there any way to have the documented behaviour in 3.12?