c++ - 这个工作线程怎么会被阻塞却显示正在运行呢?

标签 c++ multithreading c++11

我有一个运行四个工作线程的多线程任务队列。工作例程如下:

void worker() {
    task_t task;

    while (true) {
        try {
            pthread_setname_np("waiting");

            std::unique_lock<std::mutex> lock{mutex_m};

            condition_m.wait(lock, [=](){ return done_m || !deque_m.empty(); });

            if (done_m)
                return;

            // try to pop a task off the deque. Returns true iff the deque's
            // front task was moved out of the deque into task.
            if (try_pop_unsafe(task)) {
                lock.unlock();

                pthread_setname_np("RUNNING");

                task();
            }
        } catch (...) {
            // Drop it on the floor. Not ideal, but really there's nowhere
            // for them to go right now.
        }
    }
}

您会注意到有两个位置设置线程名称:在 while 循环的顶部,以及在要执行任务之前。当线程被阻塞并等待任务时,它的名称中应该显示waiting。当工作线程工作时,它应该显示 RUNNING

在调试过程中,我发现有工作线程被condition_m.wait(...)阻塞,但显示RUNNING。怎么会这样?这是 IDE 的困惑,还是工作函数中是否有一条路径可以解释它?

最佳答案

如果任务本身阻塞,它可以继续运行。

或者,如果任务引发异常,则 catch 语句仅退出函数,使线程保持在“RUNNING”状态,直到线程被加入。也许在这里引入“DEAD”或“EXCEPTION”状态可能会更好?

您在什么操作系统上运行以及使用什么 IDE?

关于c++ - 这个工作线程怎么会被阻塞却显示正在运行呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34326668/

相关文章:

c++ - 在 C++ 中将我的类分离到不同的头文件中

android - 在没有 Android Studio 的情况下为 Android 创建 (Cmake) C/C++ 库

c++ - 有没有一种方法可以更有效地将二进制 double 从文件读取到 float 数组中?

c - 线程 : value stored in heap 问题

c++ - 如何使用 std::ref?

c++ - 为什么/etc/目录下没有创建文件

c++ - 在cpp中格式化

c++ - 实现 partition_unique 和 stable_partition_unique 算法

ios - 在调试导航器或其他工具中显示线程标签

Python 线程/线程实现