在Python中检查当前线程是否为主线程 [英] Check if current thread is main thread, in Python

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

问题描述

Android 目标C 和<之前是href ="https://stackoverflow.com/questions/20530218/check-if-current-thread-is-main-thread"> C ++ ,但显然不适用于Python.如何可靠地确定当前线程是否为主线程?我可以想到一些方法,没有一种方法真正令我满意,因为考虑到与threading.MainThread相比,它可能是如此简单.

This has been answered for Android, Objective C and 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.MainThread if it existed.

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

The main thread is instantiated in threading.py like this:

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

所以一个人可以做

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

但是这个名字是固定的吗?我看到的其他代码检查了线程名称中是否包含MainThread.

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

我可以在程序启动时(即没有其他线程的时候)存储对启动线程的引用.这绝对是可靠的,但是对于这样一个简单的查询来说太麻烦了吗?

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?

是否有更简洁的方法?

推荐答案

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

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

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

以下内容可能更可靠:

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

更新:

Python 3.4引入了 threading.main_thread() ,它要好得多比以上:

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

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

更新2:

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

For Python < 3.4, perhaps the best option is:

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

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

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