0

I have created a unique pointer to an object like this:

std::unique_ptr<MyClass> myObj(new MyClass(arg1, arg2));

And there is a method there, which I need to execute in a parallel thread. I do not want to wait for it to finish. It will run a for loop and wait for something and finish in its own time.

I tried calling it like this:

std::async(std::launch::async, &MyClass::MyMethod, myObj.get(), someArg, anotherArg);

and also like this:

std::async(std::launch::async, [&] {myObj->MyMethod(someArg, anotherArg); });

Both calls succeed and execute whatever is in the method. But I am not getting any parallelism. Execution waits wherever I call this from and does not go forward until the method is finished. What would be a good way of running this method in its own thread and not wait for it? Should I use some special compiler flags to achieve this? I am using GCC 4.8.1 on Ubuntu.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Subhamoy S.
  • 6,566
  • 10
  • 37
  • 53

1 Answers1

2

The problem is with the std::future returned from std::async. Since the task is not deferred, the std::future object is being destroyed right away. This causes the destructor to block until the thread execution has finished. You need to hold onto the std::future object`.

Velox
  • 254
  • 1
  • 5
  • Could you point me to an example where this is done. My experience with std::future is very limited. – Subhamoy S. Apr 19 '14 at 00:12
  • 1
    @SubhamoySengupta It's really easy: `auto handle = std::async(....);`. The future needs to be retained further by you. If you destruct the future while the task is not complete, the destructor will block for completion. Futures are copyable objects, so you can return the future from a method/function to a caller, etc. – Kuba hasn't forgotten Monica Apr 19 '14 at 00:17