Can C++11 tell if std::thread is active?

前端 未结 2 1914
醉梦人生
醉梦人生 2021-01-05 14:32

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

相关标签:
2条回答
  • 2021-01-05 15:14

    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

    0 讨论(0)
  • 2021-01-05 15:33

    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
    }
    
    0 讨论(0)
提交回复
热议问题