The code:
from threading import Thread
from time import sleep
def f() -> None:
while True:
sleep(0.4)
print("Thread is running.")
thread = Thread(target=f, daemon=True)
thread.start()
try:
thread.join()
except KeyboardInterrupt:
print("Caught KeyboardInterrupt")
sleep(0.8)
print(f"thread._is_stopped = {thread._is_stopped}")
print(f"thread.is_alive() = {thread.is_alive()}")
sleep(0.8)
thread._is_stopped is set to True and thread.is_alive() reports False even though the thread is still alive and printing out messages to the console. This is the output:
python3 test.py
Thread is running.
Thread is running.
Thread is running.
^CCaught KeyboardInterrupt
Thread is running.
Thread is running.
thread._is_stopped = True
thread.is_alive() = False
Thread is running.
Thread is running.
Why is .is_alive() and ._is_stopped reporting that the thread is dead when the thread is clearly alive? Also if I .join() the thread again, it immediately returns which is undesirable for me.
Replacing the thread.join() with sleep(100), fixes the problem with is_alive() reporting False. The problem is that I want to know immediately when the thread really exists.
System:
- Ubuntu 22.04.2
- python 3.10.6 (pre-installed with Ubuntu)
- running it from
bash(IDLE has problems with even causing aKeyboardInterrupts when joining a thread)