-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloc.cpp
More file actions
70 lines (68 loc) · 1.74 KB
/
loc.cpp
File metadata and controls
70 lines (68 loc) · 1.74 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <thread>
#include <vector>
#include <mutex>
#include "loc.hpp"
unsigned sum_loc (const unsigned* V, size_t n) {
unsigned T = std::thread::hardware_concurrency();
std::vector<std::thread> workers(T - 1);
unsigned s = 0;
std::mutex mtx;
auto worker_proc = ([V, n, T, &s, &mtx](unsigned t) {
size_t a = n % T, b = n / T;
if (t < b) {
a = t * ++b;
} else {
a += t * b;
}
b += a;
unsigned res = 0;
for (size_t i = a; i < b; i++) {
res += V[i];
}
s += res;
});
{
for (unsigned t = 0; t < T - 1; ++t) {
workers[t] = std::thread(worker_proc, t + 1);
}
worker_proc(0);
for (unsigned t = 0; t < T - 1; ++t) {
workers[t].join();
}
}
return s;
}
unsigned sum_loc_reduce (const unsigned* V, size_t n) {
unsigned T = std::thread::hardware_concurrency();
std::vector<std::thread> workers(T - 1);
unsigned partial_sums[T];
unsigned s = 0;
std::mutex mtx;
auto worker_proc = ([V, n, T, &mtx, &partial_sums](unsigned t) {
size_t a = n % T, b = n / T;
if (t < b) {
a = t * ++b;
} else {
a += t * b;
}
b += a;
unsigned res = 0;
for (size_t i = a; i < b; i++) {
res += V[i];
}
partial_sums[t] = res;
});
{
for (unsigned t = 0; t < T - 1; ++t) {
workers[t] = std::thread(worker_proc, t + 1);
}
worker_proc(0);
for (unsigned t = 0; t < T - 1; ++t) {
workers[t].join();
}
for (size_t i = 0; i < T; ++i) {
s += partial_sums[i];
}
}
return s;
}