aboutsummaryrefslogtreecommitdiff
path: root/include/MessageQueue.hpp
blob: df331aca080ce8c696268ed7b93cb5ae02e4622f (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
#pragma once

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

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;
        }

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

        void clear() {
            std::unique_lock<std::mutex> lock(mutex);
            data_queue.clear();
        }
    private:
        std::deque<T> data_queue;
        std::mutex mutex;
        std::condition_variable cv;
        bool running;
    };
}