June 2018
Intermediate to advanced
348 pages
8h 45m
English
Modern C++ provides a mechanism to execute a task like a function that might or might not execute in parallel. Here, we are referring to std::async, which manages the threading detail internally. std::async takes a callable object as its argument and returns an std::future that will store the result or exception from the task that has been launched. Let's rewrite our previous example to calculate the sum of all elements from a vector using std::async:
// Function to calculate the sum of elements in a vector int calc_sum(std::vector<int> v) { int sum = std::accumulate(v.begin(), v.end(), 0); return sum; } int main() { std::vector<int> nums{1,2,3,4,5,6,7,8,9,10}; // task launch using std::async std::future<int> result(std::async(std::launch::async, ...Read now
Unlock full access