-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_lambda.cpp
More file actions
36 lines (29 loc) · 868 Bytes
/
thread_lambda.cpp
File metadata and controls
36 lines (29 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>
#include <thread>
#include <algorithm>
#include <cstdlib>
int main() {
unsigned long long acm1 = 0;
unsigned long long acm2 = 0;
std::vector<int> v(1024);
srand(time(nullptr));
std::generate(v.begin(), v.end(), [&v]() { return rand() % v.size(); } );
for_each(begin(v), end(v), [](int i) { std::cout << i << ' '; } );
std::thread t1([&acm1, &v] {
for (unsigned int i = 0; i < v.size() / 2; ++i) {
acm1 += v[i];
}
});
std::thread t2([&acm2, &v] {
for (unsigned int i = v.size() / 2; i < v.size(); ++i) {
acm2 += v[i];
}
});
t1.join();
t2.join();
std::cout << "acm1: " << acm1 << std::endl;
std::cout << "acm2: " << acm2 << std::endl;
std::cout << "acm1 + acm2: " << acm1 + acm2 << std::endl;
return 0;
}