-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcurrentPartition.cpp
More file actions
61 lines (53 loc) · 1.77 KB
/
ConcurrentPartition.cpp
File metadata and controls
61 lines (53 loc) · 1.77 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
#include <iostream>
#include <vector>
#include <atomic>
#include <thread>
#include <mutex>
#include <ctime>
#include <ratio>
#include <chrono>
using namespace std;
void concurrentFunc(
int from,
int to,
vector<long> &list,
vector<vector<long>> &partitions,
int hashBits,
vector<mutex> &locks
){
for (int j = from; j < to; j++) {
int partitionIndex = list[j] % hashBits;
locks[partitionIndex].lock();
partitions[partitionIndex].push_back(list[j]);
locks[partitionIndex].unlock();
}
}
double concurrentPartition(int numberOfThreads, int hashBits) {
using namespace std::chrono;
cout << "Concurrent Partition " << numberOfThreads << " " << hashBits << endl;
long numberOfTuples = 16777216;
int blockSize = numberOfTuples / numberOfThreads;
vector<long> list(numberOfTuples);;
vector<mutex> locks(hashBits);
vector<thread> threads(numberOfThreads);
for (int i = 0; i < numberOfTuples; i++) {
list[i] = i+1;
}
high_resolution_clock::time_point t1 = high_resolution_clock::now();
vector<vector<long>> partitions(hashBits);
for (int i = 0; i < numberOfThreads; i++) {
int from = i * blockSize;
int to = from + blockSize;
if (i + 1 == numberOfThreads) {
to = numberOfTuples; // work the rest
}
threads[i] = thread(concurrentFunc, from, to, ref(list), ref(partitions), hashBits, ref(locks));
}
for (int i = 0; i < numberOfThreads; i++) {
threads[i].join();
}
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
cout << to_string(time_span.count()) << endl;
return time_span.count();
}