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;
}
if (status == std::future_status::ready) { std::cout << "Thread finished" << std::endl; } else { std::cout << "Thread still running" << std::endl; } auto result = future. get(); // Get result. }
Thread get_id() function in C++ Thread::get_id() is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the value of std::thread::id thus identifying the thread associated with *this.
4) The copy constructor is deleted; threads are not copyable. No two std::thread objects may represent the same thread of execution.
The std::thread library is implemented on top of pthreads in an environment supporting pthreads (for example: libstdc++).
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With