我怎么知道一个线程是否是python中的虚拟线程?

问题描述 投票:1回答:1

我的基本问题是:如何检测当前线程是否为虚拟线程?我是线程新手,最近我在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
python multithreading apache2 apache2.4
1个回答
1
投票

您可以检查当前线程是否是threading._DummyThread的实例。

isinstance(threading.current_thread(), threading._DummyThread)

threading.py本身可以教你虚拟线程的含义:

虚拟线程类来表示此处未启动的线程。它们在死亡时不会被垃圾收集,也不能等待它们。如果他们在调用current_thread()的threading.py中调用任何东西,他们将永远在_active dict中留下一个条目。他们的目的是从current_thread()返回一些东西。它们被标记为守护进程线程,所以当我们退出时我们不会等待它们(符合先前的语义)。

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()
© www.soinside.com 2019 - 2024. All rights reserved.