Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 741
kuchejdatomas Avatar asked Feb 28 '26 15:02

kuchejdatomas


2 Answers

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()).

like image 88
Jean-François Fabre Avatar answered Mar 02 '26 05:03

Jean-François Fabre


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.

like image 24
Aleksandr Borisov Avatar answered Mar 02 '26 04:03

Aleksandr Borisov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!