我如何知道一个线程是否是 python 中的虚拟线程?

How do I know if a thread is a dummy thread in python?

我的基本问题是:如何检测当前线程是否为虚拟线程?我是线程的新手,最近我正在调试我的 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()