7

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;
}
Nicol Bolas
  • 413,367
  • 61
  • 711
  • 904
Gearoid Murphy
  • 11,387
  • 17
  • 65
  • 86
  • possible duplicate of [C++11 safely join a thread without using a try / catch block](http://stackoverflow.com/questions/15994650/c11-safely-join-a-thread-without-using-a-try-catch-block) – Nicol Bolas Aug 05 '13 at 17:59
  • 3
    `joinable` has nothing to do with whether the thread is executing. – Nicol Bolas Aug 05 '13 at 18:04
  • 2
    This linked answer is not relevant, I wanted to know how to check if a thread is still active, not when it's safe to join, bamboon's answer addresses this perfectly – Gearoid Murphy Aug 05 '13 at 19:11

2 Answers2

8

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
}
Stephan Dollberg
  • 30,359
  • 14
  • 76
  • 106
2

for what definition of "actively running code"? not that I know of, I'm not sure what state the thread is left in after it becomes joinable, in most cases I can think of you'd actually want fine grain control, like a flag set by the code running in that thread, anyway

for a platform specific solution, you could use GetThreadTimes