summaryrefslogtreecommitdiffstats
path: root/vbench/src/vbench/core/dispatcher.h
blob: 29935ef6baa6fbee7a8f2860aa5bcb38ffe7f012 (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
// Copyright 2016 Yahoo Inc. 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/sync.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;
    vespalib::Lock            _lock;
    std::vector<ThreadState*> _threads;
    bool                      _closed;

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

} // namespace vbench

#include "dispatcher.hpp"