multithreading - Calling a Function in Parallel C++ -
i want call function in parallel in c++, waits time , performs task. don't want execution flow wait function. considered using pthread in simple way again, have wait till joins !
void a_function() { /* call function waits time , perform tasks */ /* not wait above function return , continue performing background tasks */ }
note: if not perform background tasks while calling function in parallel in next cycle, function doesn't give me correct output.
thanks in advance.
use std::future
package std::async
task. wait future @ head of function ensure it's completed before next iteration, since stated next iteration depends on execution of background task.
in example below, make background task simple atomic increment of counter, , foreground task returns counter value. illustrative purposes only!
#include <iostream> #include <future> #include <thread> class foo { public: foo() : counter_(0) {} std::pair<int, std::future<void>> a_function(std::future<void>& f) { // ensure background task previous iteration // has completed f.wait(); // set task next iteration std::future<void> fut = std::async(std::launch::async, &foo::background_task, this); // work int value = counter_.load(); // return result , future next iteration return std::make_pair(value, std::move(fut)); } void background_task() { ++counter_; } private: std::atomic<int> counter_; }; int main() { // bootstrap procedure empty task... std::future<void> bleak = std::async(std::launch::deferred, [](){}); foo foo; // iterate... (size_t = 0; < 10; ++i) { // call function std::pair<int, std::future<void>> result = foo.a_function(bleak); // set future next iteration bleak = std::move(result.second); // result std::cout << result.first << "\n"; } }
Comments
Post a Comment