Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

multithreading - Check if current thread is main thread, in Python

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.

Check the thread name

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

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 MainThread is contained anywhere in the thread's name.

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?

question from:https://stackoverflow.com/questions/23206787/check-if-current-thread-is-main-thread-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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:

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

UPDATE 2:

For Python < 3.4, perhaps the best option is:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...