I am trying to distribute a loop into multiple threads, evaluate and collect the aggregated results in the main thread using C++ promises and futures as below:
std::vector<std::promise<std::tuple<uint64_t, uint64_t, uint64_t>>> promiseVector;
std::vector<std::future<std::tuple<uint64_t, uint64_t, uint64_t>>> futureVector;;
std::vector<std::thread *> threadPool;
// create threads
for(int ti = 0, initialval = 0; ti<max_num_threads; ti++, initialval += size_per_thread) {
// create promise
promiseVector.push_back(new std::promise<std::tuple<uint64_t, uint64_t, uint64_t>>(std::make_tuple(0, 0, 0)));
// create futures
futureVector.push_back(promiseVector[ti].get_future());
// create thread and start
threadPool.push_back(
new std::thread([&]{
uint64_t rv1 = 0, rv2 = 0, rv3 = 0;
// some threadwise work
for (int ri = initialval, i = 0; i < size_per_thread; ri += 8, i++) {
...
...
...
// update
rv1 = ...
rv2 = ...
rv3 = ...
}
promiseVector[ti].set_value(std::make_tuple(local_true_positive, local_false_positive, local_false_negative));
})
);
}
// accumulate results from all threads
for(int ti = 0; ti<max_num_threads; ti++) {
std::tuple<uint64_t, uint64_t, uint64_t> fval = futureVector[ti].get();
global_val1 += std::get<0>(fval);
global_val2 += std::get<1>(fval);
global_val3 += std::get<2>(fval);
}
// join all threads
for(int ti = 0; ti<max_num_threads; ti++) {
threadPool[ti]->join();
}
But it fails to compile with below error:
error: no matching constructor for initialization of 'std::promise<std::tuple<uint64_t, uint64_t, uint64_t> >' (aka 'promise<tuple<unsigned long, unsigned long, unsigned long> >')
promiseVector.push_back(new std::promise<std::tuple<uint64_t, uint64_t, uint64_t>>(std::make_tuple(0, 0, 0)));
^ ~~~~~~~~~~~~~~~~~~~~~~~~
I am new to cpp multithreading.