I have a long program with a lot of threads in it. I created a sample, short code where you can see exactly what the problem is.
from threading import Thread, active_count
import time
def func(x):
time.sleep(x)
print(active_count())
print(active_count())
t = Thread(target=func, name="thread", args=(5,))
t.start()
print("main thread finished")
Simply put - I do not understand why the main thread is still active even after the last print statement was executed.
- I defined a function func
- The first print statement prints number 1 - number of active threads. Since the thread t has not been activated yet, number 1 is correct (only main thread)
- I defined thread t and executed it.
- While the thread t sleeps, the main thread finished the last print statement and SHOULD FINISH BUT
- the thread t wakes up and prints the number of currently active threads - and the number is 2 - both the main thread and thread t are (according to python) active even though the main thread should have already finished and therefore should not be active anymore because it already printed the last line (the last print statement).
Can please someone explain to me why is that and what is the mechanism behind the main thread vs. other threads? thank you