I have an array of structure of 2 strings which I return from a function. But this function is called as part of the callable function of a thread
struct mystruct* myfunc(char* param1, int param2, int param3);
std::thread t1(myfunc, param1, param2, param3);
I understood from the std::thread documentation that the return value from myfunc will be ignored. But I need this data. Is there a way to get this data? I read there is something like std::promise and std::future but really couldn't understand what they are. Can anyone help me out with a simple example to achieve this?
Thanks a lot, in advance.
Esash
As you said, the proper way to do this is probably using std::future
and std::async
. As cppreferece sais:
The class template std::future provides a mechanism to access the result of asynchronous operations
This is where std::async
comes in. The function myfunc
will be launched using std::async
, which will return a "future" value (which we will catch later). Once you have the asynchronous function launched, you just have to ask your std::future
variable to get that return value whenever it's ready. Your code would look something like this:
// This will call myfunc asynchronously and assign its future return value to my_fut
std::future<mystruct*> my_fut = std::async(myfunc, param1, param2, param3);
/*
Do some work
*/
// We are ready to assign the return value to a variable, so we ask
// my_fut to get that "future" value we were promised.
mystruct* mptr = my_fut.get();
I think that's all you need.
As @Fransisco Callego Salido already said the only way to do what you want is to use std::async, but be careful std::async does not guarantee that your function will be run asynchronously. As cppreference says.
The template function async runs the function f asynchronously (potentially in a separate thread which may be part of a thread pool) and returns a std::future that will eventually hold the result of that function call.
In order to run myfunc asynchronously you have to pass another parameter to the constructor of std::async, the policy. Right now there are 3 policies
Another thing to remember is, that the policy is always passed as the first parameter to std::async's constructor, if you forget to pass it the std::launch::async | std::launch:deferred policy will be used! So in order guarantee an that your function is executed on a new thread you have to call it like this.
std::future<mystruct*> myfunc_future=std::async(std::launch::async, myfunc, param1, param2, param3);
mystruct* myfunc_result=myfunc.get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.