Last active
June 10, 2016 12:34
-
-
Save blippy/5ec2509a0d6a7162050a8f935cee4c5a to your computer and use it in GitHub Desktop.
Apply function concurrently on a vector of args
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See discussion at http://stackoverflow.com/questions/37727432/debugging-template-deduction-failure
Make :
g++ simult.cc -o simult -lpthreadRun: