You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/asynchronous_programming.md
+118Lines changed: 118 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -1,5 +1,8 @@
1
+
# Asynchronous Calls
1
2
In C++, asynchronous programming can be achieved using various mechanisms such as threads, `std::async`, `std::future`, and `std::promise`. One common way to create asynchronous calls is through `std::async` which runs a function asynchronously (potentially in a new thread) and returns a `std::future` that will hold the result of that function call once it completes.
2
3
4
+
5
+
## std::launch::async, std::future
3
6
Here is an example demonstrating an asynchronous call in C++ using `std::async`:
4
7
5
8
```c++
@@ -101,3 +104,118 @@ Explanation:
101
104
- After the first lambda has finished its work and has waited for the second lambda, the main thread continues and waits for the first asynchronous task to complete by calling `work_future.get()`.
102
105
103
106
By capturing by value, we ensure that each lambda has its own independent copy of the parameters, which is usually the safest way to pass parameters to asynchronous calls to avoid any potential data races or undefined behavior due to accessing shared data from multiple threads.
107
+
108
+
109
+
110
+
111
+
## Parallelization with ascync
112
+
113
+
114
+
```cpp
115
+
#include<iostream>
116
+
#include<vector>
117
+
#include<numeric>
118
+
#include<future>
119
+
#include<thread>
120
+
#include<iterator>
121
+
122
+
// Function to sum a chunk of the vector
123
+
template <typename Iterator>
124
+
longlongsum_chunk(Iterator begin, Iterator end) {
125
+
return std::accumulate(begin, end, 0LL);
126
+
}
127
+
128
+
int main() {
129
+
// Example vector
130
+
std::vector<int> vec(1000000, 1); // Vector of 1 million elements, each initialized to 1
131
+
132
+
// Determine the number of chunks based on hardware concurrency
133
+
unsigned int num_chunks = std::thread::hardware_concurrency();
134
+
if (num_chunks == 0) num_chunks = 2; // Fallback in case hardware_concurrency returns 0
135
+
136
+
std::vector<std::future<long long>> futures;
137
+
size_t chunk_size = vec.size() / num_chunks;
138
+
auto begin = vec.begin();
139
+
140
+
// Launch async tasks for each chunk
141
+
for (unsigned int i = 0; i < num_chunks; ++i) {
142
+
auto end = (i == num_chunks - 1) ? vec.end() : std::next(begin, chunk_size);
0 commit comments