-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistributedCounter1.h
More file actions
41 lines (37 loc) · 949 Bytes
/
DistributedCounter1.h
File metadata and controls
41 lines (37 loc) · 949 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
37
38
39
40
41
#ifndef DISTRIBUTED_COUNTER_H
# define DISTRIBUTED_COUNTER_H
// Implement a distributed counter with a thread local count in
// conformance with cache-conscious programming best practices in
// the lecture.
//
// Most of the complexity here is in managing the thread local counts
// as threads are created or destroyed. Study how we use various
// multithreading techniques to accurately and safely track these.
#include<mutex>
#include<shared_mutex>
#include<map>
#include<numeric>
namespace mpcs {
class DistributedCounter {
public:
typedef long long value_type;
private:
value_type count;
std::shared_mutex mutable mtx;
public:
DistributedCounter() : count(0) {}
void operator++() {
std::unique_lock lock(mtx);
++count;
}
void operator++(int) {
std::unique_lock lock(mtx);
count++;
}
value_type get() const {
std::shared_lock lock(mtx);
return count;
}
};
}
#endif