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

To my surprise, the std :: thread C ++ 11 object, which completed execution but has not yet joined, still considers the 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 supports detection if the std :: thread object continues to actively run 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; } 
+4
source share
2 answers

No, I do not think this is possible. I will also try to think about your design, and if such a check is really necessary, perhaps you are looking for something like intermittent streams from boost.

However, you can use std::async - which I would do anyway, and then rely on the std::future functions. You can

Namely, you can call std::future::wait_for with something like std::chrono::seconds(0) . This gives you a zero cost check and allows 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 } 
+6
source

What is the definition of "active code"? not that I know, I'm not sure what state the stream remains after it becomes connected, in most cases I can think about what you really want to control small grains, for example, a flag set by code running in this thread anyway

to solve a specific platform you can use GetThreadTimes

+2
source

Source: https://habr.com/ru/post/1495371/


All Articles