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`.
How to asynchronously execute method from unique_ptr to object?
-
06-07-2023 - |
Pergunta
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.
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow