multithreading - What is the optimal way to wait for multiple futures in C++11? -
i looking optimal way in terms of execution time, wait independent futures finish.
dealing 2 futures simple, 1 can have optimal way follows:
auto f1 = async(launch::async, []{ dosomething(’.’); }); auto f2 = async(launch::async, []{ dosomething(’+’); }); while (f1.wait_for(chrono::seconds(0)) != future_status::ready && f2.wait_for(chrono::seconds(0)) != future_status::ready) { }; f1.get(); f2.get();
this way, leave loop while @ least 1 of futures finished, calling .get()
both won't make program looses time.
how n futures?
if want create arbitrary number of std::futures, might put them std::vector. can loop through vector , get
results. note get
handles waiting.
//result type defined here: http://en.cppreference.com/w/cpp/thread/async template<typename f, typename... args> using asyncresult = std::result_of_t<std::decay_t<f>(std::decay_t<args>...)>; template<typename t, typename f1, typename f2> void do_par(const std::vector<t>& ts, f1&& on_t, f2&& accumulate) { //the standard doesn't require these futures correspond individual //threads, there's chance they'll implemented way. std::vector<std::future<asyncresult<f1, t>>> threads; (const t& t : ts) { threads.push_back(std::async(on_t, t)); } //think of waiting on each thread finish. (auto& future : threads) { accumulate(std::move(future)); } } template<typename t, typename f> std::vector<asyncresult<f, t>> map_par(const std::vector<t>& ts, f&& on_t) { std::vector<asyncresult<f, t>> out; do_par(ts, on_t, [&](auto&& future_){ out.push_back(future_.get()); }); return out; } std::string dosomething(const std::string&){ return std::string("yo"); }
and can do
const std::vector<std::string> results = map_par( std::vector<std::string>{".", "+", "et al"}, dosomething );
this simple map_par function isn't quite savviest solution. might set thread queue (which own thread pool) cut out overhead of spawning individual threads, context-switching overhead comes play when have more threads cpu cores. thread queue implementation might want have own async method, akin of std::async.
if want use results when come in, regardless of input order, consider setting single-reader-multiple-writer (which incidentally involves queue).
std::condition_variable helps both of above suggestions.
Comments
Post a Comment