10

How can I check if the Main Thread is alive from another ( non-daemon, child ) thread?

The child thread is a non-daemon thread and I'd like to check if the Main thread is still running or not, and stop this non-daemon thread based on the result.

( Making the thread daemon is not good for my situation because my thread writes to stdout which creates problems when the thread is set as a daemon)

Using python 2.7

5
  • What's your definition of "still running"? Do you mean still performing an operation? Or still alive?
    – aychedee
    May 3, 2014 at 10:11
  • I mean that it's still alive May 3, 2014 at 10:21
  • You could pass the stream to write to as part of the other context data given to the thread. Then there wouldn't be anything that keeps you from making the thread a daemon. May 3, 2014 at 10:36
  • @UlrichEckhardt How can I do that? I'm simply using print in the thread May 3, 2014 at 10:37
  • Don't use print but some_stream.write() instead. May 3, 2014 at 10:56

2 Answers 2

15
  • For Python 2.7 you can try this:

    for i in threading.enumerate():
       if i.name == "MainThread":
           print i.is_alive()
    

    The usage of lower camel case in function names is deprecated and so you should be using i.is_alive() instead of i.isAlive().

  • If you like one-liners try this:

    is_main_thread_active = lambda : any((i.name == "MainThread") and i.is_alive() for i in threading.enumerate())
    

    Then call is_main_thread_active() to check if the Main Thread is active.

    For one time use, however, you could use this directly without creating a function.

    any((i.name == "MainThread") and i.is_alive() for i in threading.enumerate())

  • Check this page for more info about threading.

  • In python 3.4 a dedicated function to return the main thread exists and so you can use this one liner to see if your main thread is still alive..

    threading.main_thread().is_alive()
    

Hope this helps you.

0
1

apart from what Raghav's said, you can also save the main thread in a global variable from inside it like:

mainThread = threading.currentThread() # current_thread() in py 3

then use mainThread.isAlive().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.