I am working on a program in which I would like to use async in a loop. In the sample code, I included only 10 elements there, so I could easily create an explicit variable for each element. However, in my main program, the number of elements in a vector can vary. Ideally, I would like to create a vector of asynchronous threads - one for each element in the array, which is discarded back to the async vector when I go through it. Then I want to wait for them to complete and then use "get ()" to return all my outputs.
In the code below, async will be called, assigning an explicit variable for each thread, but does anyone know how to dynamically call async in a vector without having to explicitly assign a variable to it? Ideally, I would like this program to call "std :: cout" once for each pass, and not just once.
#include <iostream> #include <vector> #include <string> #include <future> std::string hi (std::string input) { return "hello, this is " + input; } int main() { std::vector<std::string> test_vector( 10, "a test" ); std::future<std::string> a; std::future<std::string> b; for ( int i = 0; i < test_vector.size ( ); i++ ) { a = std::async(std::launch::async, hi, test_vector[i]); } std::cout << a.get() << std::endl; return 0; }
c ++ multithreading concurrency c ++ 11
Jack simpson
source share