Skip to content

Instantly share code, notes, and snippets.

@ashwin
Last active March 3, 2023 23:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashwin/9b3c5efd1edc3736f47d to your computer and use it in GitHub Desktop.
Save ashwin/9b3c5efd1edc3736f47d to your computer and use it in GitHub Desktop.
How to use async threads in C++
#include <future>
float DoWork(int idx)
{
// Do some hard computation using idx
// and internal read-only data structures
// Return the float result
}
void DoAsync()
{
// To control async threads and their results
std::vector<std::future<float>> fut_vec;
// Create 10 async threads
for (int i = 0; i < 10; ++i)
fut_vec.push_back(
std::async(DoWork, i));
// Collect results from 10 async threads
float result = 0;
for (int i = 0; i < 10; ++i)
result += fut_vec[i].get();
std::cout << "Result: " << result << std::endl;
}
// Note 1: On Linux use std::launch::async launch policy
// Else threads will execute sequentially
// fut_vec.push_back(
// std::async(std::launch::async, DoWork, i));
//
// Note 2: To call method of a class, pass pointer to object as
// first parameter:
//
//struct DoWorkClass
//{
// float DoWork(int idx) {}
//
// void DoAsync()
// {
// // ...
// fut_vec.push_back(
// std::async(std::launch::async, &DoWorkClass::DoWork, this, i);
//};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment