0

If I create an std::async object in a class, how long does the corresponding thread run? Until the desctructor of the containing class (Bar) is called?

class Bar {

public:

Bar() {
    handle = std::async(
                std::launch::async,
                &Bar:foo, this);
}

...

void Foo() {
  while (true) {//do stuff//}

}

private:
  std::future<void> handle;

};

EDIT:

How long does the thread run in the following example:

class Bar {

public:

Bar() : thread(&Bar:foo, this) {
}

...

void Foo() {
  while (true) {//do stuff//}

}

private:
  std::thread thread;

};
user695652
  • 4,105
  • 7
  • 40
  • 58

1 Answers1

2

The asynchronous operation runs until the function returns. If you have an infinite loop, it will run forever. There really isn't a safe way to "abort" an async operation. You have to use thread communication to tell it to quit.

If you destroy the associated future, it will block until the operation is done.

The thread backing the operation might run beyond that, if the implementation uses a thread pool, but you should not need to worry about that.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • Thanks, very insightful. Am I understanding you correctly that for periodic tasks (like clean up) as the function Foo in my example one should use std::threads instead of std::async? – user695652 Oct 17 '16 at 15:30
  • Note that according to the C++ standard, a compiler is allowed to terminate or optimize out a thread that will run indefinitely. – rubenvb Oct 17 '16 at 15:37