aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/monitored_refcount.cpp
blob: 3bcdfe5168118ea755fecf8ba0ccf71a398fa6b6 (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "monitored_refcount.h"
#include <cassert>

namespace vespalib {

MonitoredRefCount::MonitoredRefCount()
    : _lock(),
      _cv(),
      _refCount(0u)
{
}

MonitoredRefCount::~MonitoredRefCount()
{
    assert(_refCount == 0u);
}

void
MonitoredRefCount::retain() noexcept
{
    std::lock_guard<std::mutex> guard(_lock);
    ++_refCount;
}

void
MonitoredRefCount::release() noexcept
{
    std::lock_guard<std::mutex> guard(_lock);
    --_refCount;
    if (_refCount == 0u) {
        _cv.notify_all();
    }
}

void
MonitoredRefCount::waitForZeroRefCount()
{
    std::unique_lock<std::mutex> guard(_lock);
    _cv.wait(guard, [this] { return (_refCount == 0u); });
}

bool
MonitoredRefCount::has_zero_ref_count()
{
    std::unique_lock<std::mutex> guard(_lock);
    return (_refCount == 0u);
}

}