-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscoped_counter.tcc
84 lines (70 loc) · 1.75 KB
/
scoped_counter.tcc
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#define scoped_counter_tcc
#include "scoped_counter.h"
namespace kaiu {
/*** ScopedCounter ***/
template <typename Counter>
ScopedCounter<Counter>::ScopedCounter(const Counter initial_value) :
value(initial_value)
{
}
template <typename Counter>
void ScopedCounter<Counter>::adjust(const Delta delta)
{
if (delta == 0) {
return;
}
std::lock_guard<std::mutex> lock(zero_cv_mutex);
value += delta;
if (value == 0) {
notify();
}
}
template <typename Counter>
void ScopedCounter<Counter>::notify() const
{
zero_cv.notify_all();
}
template <typename Counter>
bool ScopedCounter<Counter>::isZero() const
{
std::lock_guard<std::mutex> lock(zero_cv_mutex);
return value == 0;
}
template <typename Counter>
void ScopedCounter<Counter>::waitForZero() const
{
std::unique_lock<std::mutex> lock(zero_cv_mutex);
zero_cv.wait(lock, [this] { return value == 0; });
}
template <typename Counter>
typename ScopedCounter<Counter>::ScopedAdjustment ScopedCounter<Counter>::delta(const Delta amount)
{
return ScopedAdjustment(*this, amount);
}
/*** ScopedCounter<Counter>::ScopedAdjustment ***/
template <typename Counter>
ScopedCounter<Counter>::ScopedAdjustment::ScopedAdjustment(
ScopedCounter<Counter>& counter, const Delta delta) :
counter(counter), delta(delta)
{
counter.adjust(delta);
}
template <typename Counter>
ScopedCounter<Counter>::ScopedAdjustment::~ScopedAdjustment()
{
counter.adjust(-delta);
}
template <typename Counter>
ScopedCounter<Counter>::ScopedAdjustment::ScopedAdjustment(ScopedAdjustment&& old) :
counter(old.counter), delta(0)
{
/*
* Don't call main constructor so we don't alter the counter and
* notify_all
*
* Zero the old instance's delta so it doesn't alter the counter and
* notify_all
*/
std::swap(delta, old.delta);
}
}