我有一个运行四个工作线程的多线程任务队列。工作例程如下:
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/