aboutsummaryrefslogtreecommitdiffstats
path: root/vbench/src/vbench/core/handler_thread.h
blob: 03157ebed862e27ee1bb3afecb8b585ae38de8ee (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include "handler.h"
#include <vespa/vespalib/util/arrayqueue.hpp>
#include <vespa/vespalib/util/thread.h>
#include <vespa/vespalib/util/runnable.h>
#include <condition_variable>

namespace vbench {

/**
 * A Handler that will forward incoming objects to another handler in
 * a separate thread. All objects are forwarded using the same thread,
 * reducing the need for synchronization in the handler forwarded
 * to. A call to join will wait until all queued object have been
 * forwarded. Object obtained after join is invoked will be discarded.
 **/
template <typename T>
class HandlerThread : public Handler<T>,
                      public vespalib::Runnable
{
private:
    std::mutex                                 _lock;
    std::condition_variable                    _cond;
    vespalib::ArrayQueue<std::unique_ptr<T> >  _queue;
    Handler<T>                                &_next;
    std::thread                                _thread;
    bool                                       _done;

    void run() override;

public:
    HandlerThread(Handler<T> &next, init_fun_t init_fun);
    ~HandlerThread();
    void handle(std::unique_ptr<T> obj) override;
    void join();
};

} // namespace vbench

#include "handler_thread.hpp"