Detect thread end

350 views Asked by At

I would like to detect thread end in c++11 but I don't know how to do, it's look like that "get" block program, here is what I've done:

void Object::init()
{
    this->thread = std::async( std::launch::async, &State::load, stateInstance );
}

/* A method in a loop */
void Object::run()
{
    bool ready = this->thread.get();
    if( ready )
    {
      /* do something */
    }
    else
    {
       /* draw interface, manage event, … */
    }
}

My program don't go in the "else" in "run" method, program is stuck on "this->thread->get()" while state isn't load.

How can I handle that?

Thanks!

2

There are 2 answers

0
sehe On BEST ANSWER

I'm unsure what the trouble is, but here's an idea using wait_for (compiled on Coliru):

#include <future>
#include <chrono>
#include <iostream>

struct State
{
    void load() { 
        std::cout << "working\n";
        std::this_thread::sleep_for(std::chrono::seconds(4));
        std::cout << "done\n";
    }
};

struct Object
{
    /* A method in a loop */
    bool run()
    {
        switch(future.wait_for(std::chrono::milliseconds(100)))
        {
            case std::future_status::ready:
                {
                    /* do something */
                }
                return false;
            case std::future_status::timeout:
                {
                    /* draw interface, manage event, … */
                }
            case std::future_status::deferred:
            default:
                return true;
        }
    }

    Object()  { init(); }
    ~Object() { if (future.valid()) future.wait(); }
  private:
    void init()
    {
        future = std::async(std::launch::async, &State::load, &stateInstance);
    }

    State stateInstance;
    std::future<void> future;
};

int main()
{
    Object test;

    while (test.run());
}
5
dzada On

try this

while(!this->thread.valid())
{ //do smthg
}else{
}

Your get locks, because get wants to retrieve the result of the future this->thread. therefor it does wait for this result to be ready, and returns it.

valid just tell if this future result is ready