我的基本问题是:如何检测当前线程是否是虚拟线程?我对线程很陌生,最近在Apache2 2/Flask应用程序中调试了一些代码,并认为它可能很有用。我得到了一个翻转错误,在主线程上成功地处理了请求,在虚拟线程上成功地处理了请求,然后又在主线程上成功地处理了请求,等等。
就像我说的,我正在使用Apache2和烧瓶,这两者的结合似乎创建了这些虚拟线程。如果有人能教我的话,我也会有兴趣了解更多这方面的知识。
我的代码用于打印有关在服务上运行的线程的信息,如下所示:
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发布于 2019-02-27 20:01:17
您可以检查当前线程是否是threading._DummyThread的实例。
isinstance(threading.current_thread(), threading._DummyThread)threading.py本身可以教你什么是虚拟线程:
表示未在此处启动的线程的虚拟线程类。这些不是死后收集的垃圾,也不能等待。如果它们调用threading.py中调用current_thread()的任何内容,则会在_active dict中永久保留一个条目。他们的目的是从current_thread()返回一些东西。它们被标记为守护进程线程,因此我们在退出时不会等待它们(符合以前的语义)。 def current_thread():“返回当前线程对象,对应于调用方的控制线程。如果调用方的控制线程不是通过线程模块创建的,则返回功能有限的虚拟线程对象。”try:返回_activeget_ident(),除了KeyError:返回_DummyThread()
https://stackoverflow.com/questions/54912544
复制相似问题