检查主线程是否仍在另一个线程中 [英] Check if the Main Thread is still alive from another thread

查看:92
本文介绍了检查主线程是否仍在另一个线程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查主线程是否从另一个(非守护进程,子线程)线程中恢复运行?

子线程是非守护线程,我想检查主线程是否仍在运行,并根据结果停止该非守护线程.

(使线程守护程序不适用于我的情况,因为我的线程写入 stdout ,当将线程设置为守护程序时会产生问题)

使用python 2.7

解决方案

  • 对于Python 2.7,您可以尝试以下操作:

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

    不建议在函数名称中使用小写驼峰,因此您应该使用i.is_alive()而不是i.isAlive().

  • 如果您喜欢单线,请尝试以下操作:

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

    然后调用is_main_thread_active()以检查主线程是否处于活动状态.

    但是,一次使用,您可以直接使用它而无需创建函数.

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

  • 检查此页面以获取有关线程化的更多信息.

  • p>
  • 在python 3.4中,存在一个专用函数来返回主线程,因此您可以使用此衬套查看您的主线程是否仍然存在..

    threading.main_thread().is_alive()
    

希望这对您有所帮助.

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

解决方案

  • 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.

这篇关于检查主线程是否仍在另一个线程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆