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

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

namespace vespalib {

InvokeServiceImpl::InvokeServiceImpl(duration napTime)
    : _naptime(napTime),
      _now(steady_clock::now()),
      _lock(),
      _cond(),
      _currId(0),
      _closed(false),
      _toInvoke(),
      _thread(std::make_unique<std::thread>([this]() { runLoop(); }))
{
}

InvokeServiceImpl::~InvokeServiceImpl()
{
    {
        std::lock_guard guard(_lock);
        assert(_toInvoke.empty());
        _closed = true;
        _cond.notify_all();
    }
    _thread->join();
}

class InvokeServiceImpl::Registration : public IDestructorCallback {
public:
    Registration(InvokeServiceImpl * service, uint64_t id) noexcept
        : _service(service),
          _id(id)
    { }
    Registration(const Registration &) = delete;
    Registration & operator=(const Registration &) = delete;
    ~Registration() override{
        _service->unregister(_id);
    }
private:
    InvokeServiceImpl * _service;
    uint64_t            _id;
};

std::unique_ptr<IDestructorCallback>
InvokeServiceImpl::registerInvoke(InvokeFunc func) {
    std::lock_guard guard(_lock);
    uint64_t id = _currId++;
    _toInvoke.emplace_back(id, std::move(func));
    _cond.notify_all();
    return std::make_unique<Registration>(this, id);
}

void
InvokeServiceImpl::unregister(uint64_t id) {
    std::lock_guard guard(_lock);
    auto found = std::find_if(_toInvoke.begin(), _toInvoke.end(), [id](const IdAndFunc & a) {
        return id == a.first;
    });
    assert (found != _toInvoke.end());
    _toInvoke.erase(found);
    _cond.notify_all();
}

void
InvokeServiceImpl::runLoop() {
    std::unique_lock guard(_lock);
    while ( ! _closed ) {
        _now.store(steady_clock::now(), std::memory_order_relaxed);
        for (auto & func: _toInvoke) {
            func.second();
        }
        _cond.wait_for(guard, _naptime);
    }
}

}