Gea*_*phy 5 c++ multithreading c++11
令我惊讶的是,一个已经完成执行但尚未加入的C++ 11 std :: thread对象仍然被认为是一个活动的执行线程.下面的代码示例(在Xubuntu 13.03上使用g ++ 4.7.3构建)说明了这一点.有谁知道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;
}
Run Code Online (Sandbox Code Playgroud)
不,我不认为这是可能的.我也会尝试考虑你的设计,如果确实需要这样的检查,也许你正在寻找像boost这样的可中断线程.
但是,你可以使用std::async- 无论如何我会做 - 然后依靠std::future你提供的功能.
也就是说,你可以std::future::wait_for用类似的东西打电话std::chrono::seconds(0).这为您提供零成本检查,并使您能够比较std::future_status返回的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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10824 次 |
| 最近记录: |