aboutsummaryrefslogtreecommitdiff
path: root/include/MessageQueue.hpp
blob: 30826f48fb3e33a1e8d44e097fca0b51b93cad04 (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
#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;
        }

        // Returns true from |callback| to remove the element
        void erase_if(std::function<bool(T&)> callback) {
            std::unique_lock<std::mutex> lock(mutex);
            for(auto it = data_queue.begin(); it != data_queue.end();) {
                if(callback(*it))
                    it = data_queue.erase(it);
                else
                    ++it;
            }
        }
    private:
        std::deque<T> data_queue;
        std::mutex mutex;
        std::condition_variable cv;
        bool running;
    };
}