I'm trying to understand the std::async
, std::future
system. What I don't quite understand is how you deal with running multiple async "tasks", and then, based on what returns first, second, etc, running some additional code.
Example: Let's say your main thread is in a simple loop. Now, based on user input, you run several functions via std::async
, and save the futures in a std::list
.
My issue is, how do I pass information back from the std::async
function that can specify which future is complete?
My main thread is basically in a message loop, and what I need to do is have a function run by std::async
be able to queue a message that somehow specifies which future is complete. The issue is that the function doesn't have access to the future.
Am I just missing something?
Here is some pseudo-code of what I'm trying to accomplish; extra points if there is a way to also have a way to have a way to make a call to "cancel" the request using a cancelation token.
class RequestA
{
public:
int input1;
int output1;
};
main()
{
while(1)
{
//check for completion
// i.e. pop next "message"
if(auto *completed_task = get_next_completed_task())
{
completed_task->run_continuation();
}
// other code to handle user input
if(userSaidRunA())
{
// note that I don't want to use a raw pointer but
// am not sure how to use future for this
RequestA *a = new RequestA();
run(a, OnRequestTypeAComplete);
}
}
}
void OnRequestTypeAComplete(RequestA &req)
{
// Do stuff with req, want access to inputs and output
}
std::async
operates on aCallable
object. You could, for instance, assign an ID number to that object when you create it, and store that ID in the list with thestd::future
object. TheCallable
could then post its ID to the message queue and the message handler can look for the ID in the list. Another option would be to add an emptystd::future
to the list first, then pass an iterator to that object to theCallable
so it can post it back to the message queue. Move the result ofstd::async
to that existingstd::future
object, and have the message handler use the posted iterator – Esmeraldaesmereldathen()
, and waiting for any of a whole range of futures withwhen_any()
/wait_any()
. – Osana