简体   繁体   中英

Main thread in Python

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.

  1. I defined a function func
  2. 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)
  3. I defined thread t and executed it.
  4. While the thread t sleeps, the main thread finished the last print statement and SHOULD FINISH BUT
  5. 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM