在 Python 中检查当前线程是否为主线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23206787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:30:00  来源:igfitidea点击:

Check if current thread is main thread, in Python

pythonmultithreading

提问by jonny

This has been answered for Android, Objective Cand C++before, but apparently not for Python. How do I reliably determine whether the current thread is the main thread? I can think of a few approaches, none of which really satisfy me, considering it could be as easy as comparing to threading.MainThreadif it existed.

之前已经针对AndroidObjective CC++回答了这个问题,但显然没有针对 Python回答。如何可靠地确定当前线程是否为主线程?我能想到一些方法,但没有一个真正让我满意,因为它可以像比较threading.MainThread它是否存在一样简单。

Check the thread name

检查线程名称

The main thread is instantiated in threading.pylike this:

主线程实例化threading.py如下:

Thread.__init__(self, name="MainThread")

so one could do

所以可以做

if threading.current_thread().name == 'MainThread'

but is this name fixed? Other codes I have seen checked whether MainThreadis contained anywhere in the thread's name.

但是这个名字是固定的吗?我见过的其他代码检查是否MainThread包含在线程名称中的任何位置。

Store the starting thread

存储起始线程

I could store a reference to the starting thread the moment the program starts up, i.e. while there are no other threads yet. This would be absolutely reliable, but way too cumbersome for such a simple query?

我可以在程序启动时存储对起始线程的引用,即当还没有其他线程时。这绝对可靠,但对于这样一个简单的查询来说太麻烦了?

Is there a more concise way of doing this?

有没有更简洁的方法来做到这一点?

采纳答案by s16h

The problem with threading.current_thread().name == 'MainThread'is that one can always do:

问题threading.current_thread().name == 'MainThread'在于,人们总是可以做到:

threading.current_thread().name = 'MyName'
assert threading.current_thread().name == 'MainThread' # will fail

Perhaps the following is more solid:

也许以下内容更可靠:

threading.current_thread().__class__.__name__ == '_MainThread'

Having said that, one may still cunningly do:

话虽如此,人们可能仍然狡猾地这样做:

threading.current_thread().__class__.__name__ = 'Grrrr'
assert threading.current_thread().__class__.__name__ == '_MainThread' # will fail

But this option still seems better; "after all, we're all consenting adults here."

但是这个选项似乎仍然更好;“毕竟,我们这里都是成年人。”

UPDATE:

更新:

Python 3.4 introduced threading.main_thread()which is much better than the above:

引入的 Python 3.4threading.main_thread()比上面的要好得多:

assert threading.current_thread() is threading.main_thread()

UPDATE 2:

更新 2:

For Python < 3.4, perhaps the best option is:

对于 Python < 3.4,也许最好的选择是:

isinstance(threading.current_thread(), threading._MainThread)

回答by asherbar

If, like me, accessing protected attributes gives you the Heebie-jeebies, you may want an alternative for using threading._MainThread, as suggested. In that case, you may exploit the fact that only the Main Thread can handle signals, so the following can do the job:

如果像我一样,访问受保护的属性会给您带来 Heebie-jeebies,那么您可能需要使用 的替代方法threading._MainThread,如建议的。在这种情况下,您可以利用只有主线程可以处理信号的事实,因此以下可以完成这项工作:

import signal
def is_main_thread():
    try:
        # Backup the current signal handler
        back_up = signal.signal(signal.SIGINT, signal.SIG_DFL)
    except ValueError:
        # Only Main Thread can handle signals
        return False
    # Restore signal handler
    signal.signal(signal.SIGINT, back_up)
    return True

Updated to address potential issue as pointed out by @user4815162342.

更新以解决@user4815162342 指出的潜在问题。

回答by wim

The answers here are old and/or bad, so here's a current solution:

这里的答案是旧的和/或不好的,所以这是一个当前的解决方案:

if threading.current_thread() is threading.main_thread():
    ...

This method is available since Python 3.4+.

此方法自 Python 3.4+ 起可用。