Skip to content

Instantly share code, notes, and snippets.

@ayushgun
Last active August 20, 2023 16:20
Show Gist options
  • Save ayushgun/91d9290d503cbd75e6e9f42791fc03e0 to your computer and use it in GitHub Desktop.
Save ayushgun/91d9290d503cbd75e6e9f42791fc03e0 to your computer and use it in GitHub Desktop.
Example of usage of std::future and std::async for multithreaded computation.
#include <future>
#include <iostream>
#include <numeric>
#include <vector>
// Returns the sum of all integers between [1, n]
int sum(const unsigned int n) {
std::vector<int> numbers(n);
std::iota(numbers.begin(), numbers.end(), 1);
return std::accumulate(numbers.begin(), numbers.end(), 0);
}
// Performs some arbitrary task
void task() {
std::cout << "Executing task...\n";
constexpr int num_tasks = 500;
std::vector<int> result;
for (int i = 0; i < num_tasks; ++i) {
result.push_back(i);
}
}
int main() {
// Spawns two threads to complete the calculations, storing the result in a
// future. Uses std::launch::async to launch the thread right now
std::future<int> a = std::async(std::launch::async, sum, 500);
std::future<int> b = std::async(std::launch::async, sum, 750);
// Run some arbitrary task on the main thread while the multithreaded
// computations are running
task();
std::cout << "Computation result: " << a.get() + b.get() << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment