Skip to content

Instantly share code, notes, and snippets.

@blippy
Last active June 10, 2016 12:34
Show Gist options
  • Select an option

  • Save blippy/5ec2509a0d6a7162050a8f935cee4c5a to your computer and use it in GitHub Desktop.

Select an option

Save blippy/5ec2509a0d6a7162050a8f935cee4c5a to your computer and use it in GitHub Desktop.
Apply function concurrently on a vector of args
#include <functional>
#include <iostream>
#include <string>
#include <future>
#include <thread>
#include <vector>
#include <unistd.h> // for sleep. Not needed generally
// re-usable code for things you want to do concurrently
template<typename T, typename U>
std::vector<T> simult(std::function<T(U)> func, std::vector<U> const &args)
{
std::vector<std::future<T>> fs;
for(auto& a:args) fs.push_back(std::async(func, a));
std::vector<T> results;
for(auto &f:fs) results.push_back(f.get());
return results;
}
// declare a function that does what you want
std::string fn(int i)
{
sleep(i); // number of seconds to sleep for
std::cout << "Exiting after pausing " << i << " seconds\n";
return std::to_string(i+1);
}
int main()
{
std::vector<int> args { 6, 5, 7 };
std::vector<std::string> results = simult(std::function<std::string (int)>(fn), args);
std::cout << "Results are:\n";
for(auto&r:results) std::cout << r << "\n"; //results are returned in correct order
return 0;
}
@blippy

blippy commented Jun 9, 2016

Copy link
Copy Markdown
Author

See discussion at http://stackoverflow.com/questions/37727432/debugging-template-deduction-failure

Make : g++ simult.cc -o simult -lpthread

Run:

time -p simult
Exiting after pausing 5 seconds
Exiting after pausing 6 seconds
Exiting after pausing 7 seconds
Results are:
7
6
8
real 7.00
user 0.00
sys 0.00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment