aboutsummaryrefslogtreecommitdiffstats
path: root/vbench/src/vbench/core/handler_thread.hpp
blob: 3373e196ab7f1eaf3d987b4947362eb973401c63 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

namespace vbench {

template <typename T>
void
HandlerThread<T>::run()
{
    for (;;) {
        std::unique_lock guard(_lock);
        while (!_done && _queue.empty()) {
            _cond.wait(guard);
        }
        if (_done && _queue.empty()) {
            return;
        }
        assert(!_queue.empty());
        std::unique_ptr<T> obj(std::move(_queue.access(0)));
        _queue.pop();
        guard.unlock(); // UNLOCK
        _next.handle(std::move(obj));
    }
}

template <typename T>
HandlerThread<T>::HandlerThread(Handler<T> &next, init_fun_t init_fun)
    : _lock(),
      _cond(),
      _queue(),
      _next(next),
      _thread(),
      _done(false)
{
    _thread = vespalib::thread::start(*this, init_fun);
}

template <typename T>
HandlerThread<T>::~HandlerThread()
{
    if (!_done) {
        join();
    }
    assert(_queue.empty());
}

template <typename T>
void
HandlerThread<T>::handle(std::unique_ptr<T> obj)
{
    std::unique_lock guard(_lock);
    if (!_done) {
        if (_queue.empty()) {
            _cond.notify_one();
        }
        _queue.push(std::move(obj));
    }
}

template <typename T>
void
HandlerThread<T>::join()
{
    {
        std::lock_guard guard(_lock);
        _done = true;
        _cond.notify_one();
    }
    _thread.join();
}

} // namespace vbench