Concurrency and Source Panels
Async Future Sum
Launch a small asynchronous task and collect its value through a future.
Async Future Sum
async_future_sum.cpp
#include <future>
#include <iostream>
int computeSubtotal(int base) {
int doubled = base * 2;
return doubled + 1;
}
int main() {
int base = ;
auto subtotal = std::async(std::launch::async, computeSubtotal, base);
int result = subtotal.get();
int finalScore = result + base;
std::cout << "base=" << base << std::endl;
std::cout << "final=" << finalScore << std::endl;
return 0;
}
#include <future>
#include <iostream>
int computeSubtotal(int base) {
int doubled = base * 2;
return doubled + 1;
}
int main() {
int base = ;
auto subtotal = std::async(std::launch::async, computeSubtotal, base);
int result = subtotal.get();
int finalScore = result + base;
std::cout << "base=" << base << std::endl;
std::cout << "final=" << finalScore << std::endl;
return 0;
}
#include <future>
#include <iostream>
int computeSubtotal(int base) {
int doubled = base * 2;
return doubled + 1;
}
int main() {
int base = ;
auto subtotal = std::async(std::launch::async, computeSubtotal, base);
int result = subtotal.get();
int finalScore = result + base;
std::cout << "base=" << base << std::endl;
std::cout << "final=" << finalScore << std::endl;
return 0;
}
future
`std::future::get()` waits for the asynchronous task and returns its result.
task
The task body is separate from the caller, so replay can show a worker thread producing the subtotal before the caller uses it.