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

#pragma once

#include "handler.h"
#include "provider.h"
#include "closeable.h"
#include <vespa/vespalib/util/gate.h>
#include <vector>

namespace vbench {

/**
 * Dispatch objects between threads. Objects received through the
 * Handler interface will be passed along to Components requesting
 * objects through the Provider interface. If there are no components
 * currently waiting for objects, the objects will be passed along to
 * a predefined fallback handler instead. A closed dispatcher will
 * provide nil objects and handle incoming objects by deleting them.
 **/
template <typename T>
class Dispatcher : public Handler<T>,
                   public Provider<T>,
                   public Closeable
{
private:
    struct ThreadState {
        std::unique_ptr<T> object;
        vespalib::Gate   gate;
    };

    Handler<T>               &_fallback;
    mutable std::mutex        _lock;
    std::vector<ThreadState*> _threads;
    bool                      _closed;

public:
    explicit Dispatcher(Handler<T> &fallback);
    ~Dispatcher() override;
    bool waitForThreads(size_t threads, size_t pollCnt) const;
    void close() override;
    void handle(std::unique_ptr<T> obj) override;
    std::unique_ptr<T> provide() override;
};

} // namespace vbench

#include "dispatcher.hpp"