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

#pragma once

#include "closeable.h"
#include <vespa/vespalib/util/priority_queue.h>
#include <memory>
#include <mutex>
#include <condition_variable>

namespace vbench {

/**
 * A thread-safe priority queue keeping track of objects queued
 * according to an abstract time line. After a time queue is closed,
 * all incoming objects will be deleted.
 **/
template <typename T>
class TimeQueue : public Closeable
{
private:
    struct Entry {
        std::unique_ptr<T> object;
        double time;
        Entry(std::unique_ptr<T> obj, double t) noexcept : object(std::move(obj)), time(t) {}
        Entry(Entry &&rhs) noexcept : object(std::move(rhs.object)), time(rhs.time) {}
        Entry &operator=(Entry &&rhs) noexcept {
            object = std::move(rhs.object);
            time = rhs.time;
            return *this;
        }
        bool operator<(const Entry &rhs) const noexcept {
            return (time < rhs.time);
        }
    };

    std::mutex                     _lock;
    std::condition_variable        _cond;
    double                         _time;
    double                         _window;
    double                         _tick;
    vespalib::PriorityQueue<Entry> _queue;
    bool                           _closed;

public:
    TimeQueue(double window, double tick);
    ~TimeQueue();
    void close() override;
    void discard();
    void insert(std::unique_ptr<T> obj, double time);
    bool extract(double time, std::vector<std::unique_ptr<T> > &list, double &delay);
};

} // namespace vbench

#include "time_queue.hpp"