【问题标题】:Can C++11 tell if std::thread is active?C++11 可以判断 std::thread 是否处于活动状态?
【发布时间】:2013-08-05 17:35:36
【问题描述】:

令我惊讶的是,一个已完成执行但尚未加入的 C++11 std::thread 对象仍然是 considered 一个活动的执行线程。这在以下代码示例中进行了说明(基于带有 g++ 4.7.3 的 Xubuntu 13.03 构建)。有谁知道 C++11 标准是否提供了一种方法来检测 std::thread 对象是否仍在主动运行代码?

#include <thread>
#include <chrono>
#include <iostream>
#include <pthread.h>
#include <functional>
int main() {
    auto lambdaThread = std::thread([](){std::cout<<"Excuting lambda thread"<<std::endl;});
    std::this_thread::sleep_for(std::chrono::milliseconds(250));
    if(lambdaThread.joinable()) {
        std::cout<<"Lambda thread has exited but is still joinable"<<std::endl;
        lambdaThread.join();
    }
    return 0;
}

【问题讨论】:

标签: c++ multithreading c++11


【解决方案1】:

不,我认为这是不可能的。我也会尝试考虑您的设计,如果确实需要这样的检查,也许您正在寻找类似 boost 中的可中断线程之类的东西。

但是,您可以使用 std::async(无论如何我都会这样做),然后依靠 std::future 为您提供的功能。

即,您可以使用std::chrono::seconds(0) 之类的名称致电std::future::wait_for。这为您提供了零成本检查,并使您能够比较wait_for 返回的std::future_status

auto f = std::async(foo);
...
auto status = f.wait_for(std::chrono::seconds(0));
if(status == std::future_status::timeout) {
    // still computing
}
else if(status == std::future_status::ready) {
    // finished computing
}
else {
    // There is still std::future_status::defered
}

【讨论】:

  • 这是一个不错的解决方案
  • 值得注意的是,这是 c++11,所以如果你没有可用的信号量,那么使用信号量可能必须是解决方案
【解决方案2】:

对于“主动运行的代码”的定义是什么?不是我所知道的,我不确定线程​​变为可连接后处于什么状态,在大多数情况下,我认为您实际上需要细粒度控制,例如由在该线程中运行的代码设置的标志,无论如何

对于特定于平台的解决方案,您可以使用 GetThreadTimes

【讨论】:

  • 感谢您的回答,但我正在寻找通用机制
猜你喜欢
  • 2017-06-30
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多