可以C ++ 11告诉std ::线程是否活动? [英] Can C++11 tell if std::thread is active?

查看:203
本文介绍了可以C ++ 11告诉std ::线程是否活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感到惊讶的是,一个已经完成执行但尚未加入的C ++ 11 std :: thread对象仍然是考虑了一个活动的执行线程。这在下面的代码示例中说明(基于Xubuntu 13.03与g ++ 4.7.3)。有没有人知道C ++ 11标准是否提供了一种检测std ::线程对象是否仍在正在运行代码的方法?

  #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线程已退出但仍可加入<< std :: endl;
lambdaThread.join();
}
return 0;
}


解决方案

认为这是可能的。我也会尝试想想你的设计,如果这样的检查是真的有必要,也许你正在寻找一些类似于中断的线程从boost。



但是,你可以使用 std :: async - 我会这样做 - 然后依靠 std :: future



也就是说,您可以致电 std :: chrono :: seconds(0)。$ c> std :: future :: 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){
//仍在计算
}
else if(status == std :: future_status :: ready){
//完成计算
}
else {
//仍然有std :: future_status :: defered
}


To my surprise, a C++11 std::thread object that has finished executing, but has not yet been joined is still considered an active thread of execution. This is illustrated in the following code example (built on Xubuntu 13.03 with g++ 4.7.3). Does anyone know if the C++11 standard provides a means to detect if a std::thread object is still actively running code?

#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;
}

解决方案

No, I don't think that this is possible. I would also try to think about your design and if such a check is really necessary, maybe you are looking for something like the interruptible threads from boost.

However, you can use std::async - which I would do anyway - and then rely on the features std::future provides you.

Namely, you can call std::future::wait_for with something like std::chrono::seconds(0). This gives you a zero-cost check and enables you to compare the std::future_status returned by wait_for.

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告诉std ::线程是否活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆