python - python 中如何知道线程是否为虚拟线程?

标签 python multithreading apache2 apache2.4

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

相关文章:

c++ - 在 C++ 中终止一个分离的线程(从其中)

ubuntu - Ubuntu 中的 Apache2 和 ServerRoot 指令

caching - 需要帮助分析 VarnishStat 结果

python - 如何确定 CSV 文件的编码?

python - 如何在 Python Web 机器人中有效地实现多线程/多处理?

python - 如何循环遍历循环列表,同时查看当前元素的前后?

java - 如何从线程中捕获异常

php - 我如何判断我的 Apache2+PHP 是否使用 CGI/FCGI?

python - 如何并排显示 plt.imshow 的 2 列,Python

javascript - 使用python下载动态加载的网页