aboutsummaryrefslogtreecommitdiff
path: root/include/MessageQueue.hpp
blob: 1e481029add25535c2bdb879e59d7027dff71b80 (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#pragma once

#include <deque>
#include <mutex>
#include <condition_variable>
#include <optional>
#include <functional>

namespace QuickMedia {
    template <typename T>
    class MessageQueue {
    public:
        MessageQueue() : running(true) {

        }
    
        void push(T data) {
            std::unique_lock<std::mutex> lock(mutex);
            data_queue.push_back(std::move(data));
            cv.notify_one();
        }

        std::optional<T> pop_wait() {
            std::unique_lock<std::mutex> lock(mutex);
            if(!running)
                return std::nullopt;
            while(data_queue.empty() && running) cv.wait(lock);
            if(!running)
                return std::nullopt;
            T data = std::move(data_queue.front());
            data_queue.pop_front();
            return data;
        }

        std::optional<T> pop_if_available() {
            std::unique_lock<std::mutex> lock(mutex);
            if(data_queue.empty())
                return std::nullopt;
            T data = std::move(data_queue.front());
            data_queue.pop_front();
            return data;
        }

        void close() {
            std::unique_lock<std::mutex> lock(mutex);
            running = false;
            data_queue.clear();
            cv.notify_one();
        }

        void clear() {
            std::unique_lock<std::mutex> lock(mutex);
            data_queue.clear();
        }

        void restart() {
            std::unique_lock<std::mutex> lock(mutex);
            running = true;
        }

        // Return true from |callback| to remove the element
        int erase_if(std::function<bool(T&)> callback) {
            std::unique_lock<std::mutex> lock(mutex);
            int removed = 0;
            for(auto it = data_queue.begin(); it != data_queue.end();) {
                if(callback(*it)) {
                    it = data_queue.erase(it);
                    ++removed;
                } else {
                    ++it;
                }
            }
            return removed;
        }

        bool is_running() const {
            return running;
        }
    private:
        std::deque<T> data_queue;
        std::mutex mutex;
        std::condition_variable cv;
        bool running;
    };
}