-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParallelSum.cpp
More file actions
54 lines (40 loc) · 1.05 KB
/
ParallelSum.cpp
File metadata and controls
54 lines (40 loc) · 1.05 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* Sum an array with two threads in parallel */
#include <iostream>
#include <thread>
#include <mutex>
bool first = true;
const int NUM = 1000;
std::mutex mutex_lock;
int add(const int (&a)[NUM], const int (&b)[NUM], int &sum){
int offset = 1;
mutex_lock.lock();
if (first == true){
first = false;
offset = 0;
}
mutex_lock.unlock();
int res = 0;
for (int i = 0; 2 * i + offset < NUM; i++){
res += a[2 * i + offset] + b[2 * i + offset];
}
mutex_lock.lock();
sum += res;
mutex_lock.unlock();
return 0;
}
int main() {
int a[NUM], b[NUM];
int sum = 0, regular_sum = 0;
for (int i = 0; i < NUM; i++){
a[i] = i;
b[i] = i;
regular_sum += a[i] + b[i];
}
std::thread worker1(add, std::ref(a), std::ref(b), std::ref(sum));
std::thread worker2(add, std::ref(a), std::ref(b), std::ref(sum));
worker1.join();
worker2.join();
std::cout << "Sum: " << regular_sum << std::endl;
std::cout << "Parallel sum: " << sum << std::endl;
return 0;
}