可以C ++ 11告诉std ::线程是否活动? [英] Can C++11 tell if std::thread is active?
问题描述
#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屋!