Last active
March 3, 2023 23:18
-
-
Save ashwin/9b3c5efd1edc3736f47d to your computer and use it in GitHub Desktop.
How to use async threads in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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