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.
Can please someone explain to me why is that and what is the mechanism behind the main thread vs. other threads? thank you
You must be used to compiled languages like C, where exiting the main routine kills everything.
In Python, reaching the end of the main thread doesn't destroy the other threads.
In fact, you cannot really destroy threads, this must be a collaborative task (ex: setting a flag or sending an event so the thread understand it must quit its loop: in your case, you may want to segment your time.sleep()
and check for a flag in between, so you can return from the thread if needed)
So when the main thread ends its execution, the python interpreter waits for all threads to finish before exiting.
Note that it's much better to materialize this wait using the join
method ( t.start()
).
To achieve what you want you need to mark your thread as daemon before starting it:
t = Thread(...)
t.daemon = True
t.start()
See the docs https://docs.python.org/2/library/threading.html#thread-objects :
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.
The main thread is not a daemon, so marking your spawned threads as daemons allows you to exit your program as soon as your main thread ends.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.