threading.current_thread()的问题name ==’MainThread’是一个可以随时做的事情:
threading.current_thread().name = 'MyName'
assert threading.current_thread().name == 'MainThread' # will fail
以下是更可靠的:
threading.current_thread().__class__.__name__ == '_MainThread'
话虽如此,人们仍然可以狡猾地做:
threading.current_thread().__class__.__name__ = 'Grrrr'
assert threading.current_thread().__class__.__name__ == '_MainThread' # will fail
更新:
assert threading.current_thread() == threading.main_thread()
更新2:
如下面的评论所述,由user1300959提供,另一种可行且干净的选项是:
isinstance(threading.current_thread(), threading._MainThread)