我的基本问题是:如何检测当前线程是否是虚拟线程?我是线程新手,最近在我的 Apache2/Flask 应用程序中调试一些代码,并认为它可能有用。我收到一个翻转错误,其中请求在主线程上成功处理,在虚拟线程上处理失败,然后再次在主线程上成功处理,等等。
就像我说的,我正在使用 Apache2 和 Flask,这似乎是它们的组合创建了这些虚拟线程。如果有人可以教我,我也有兴趣了解更多信息。
我的代码旨在打印有关服务上运行的线程的信息,如下所示:
def allthr_info(self):
"""Returns info in JSON form of all threads."""
all_thread_infos = Queue()
for thread_x in threading.enumerate():
if thread_x is threading.current_thread() or thread_x is threading.main_thread():
continue
info = self._thr_info(thread_x)
all_thread_infos.put(info)
return list(all_thread_infos.queue)
def _thr_info(self, thr):
"""Consolidation of the thread info that can be obtained from threading module."""
thread_info = {}
try:
thread_info = {
'name': thr.getName(),
'ident': thr.ident,
'daemon': thr.daemon,
'is_alive': thr.is_alive(),
}
except Exception as e:
LOGGER.error(e)
return thread_info
最佳答案
您可以检查当前线程是否是threading._DummyThread
的实例。
isinstance(threading.current_thread(), threading._DummyThread)
threading.py
本身可以教你什么是虚拟线程:
Dummy thread class to represent threads not started here. These aren't garbage collected when they die, nor can they be waited for. If they invoke anything in threading.py that calls current_thread(), they leave an entry in the _active dict forever after. Their purpose is to return something from current_thread(). They are marked as daemon threads so we won't wait for them when we exit (conform previous semantics).
def current_thread(): """Return the current Thread object, corresponding to the caller's thread of control. If the caller's thread of control was not created through the threading module, a dummy thread object with limited functionality is returned. """ try: return _active[get_ident()] except KeyError: return _DummyThread()
关于python - python 中如何知道线程是否为虚拟线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54912544/