summaryrefslogtreecommitdiff
path: root/Externals/discord-rpc/src/msg_queue.h
blob: 77f380e7053c98416a527c4dae47ab0c5c7ca242 (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
#pragma once

#include <atomic>

// A simple queue. No locks, but only works with a single thread as producer and a single thread as
// a consumer. Mutex up as needed.

template <typename ElementType, size_t QueueSize>
class MsgQueue {
    ElementType queue_[QueueSize];
    std::atomic_uint nextAdd_{0};
    std::atomic_uint nextSend_{0};
    std::atomic_uint pendingSends_{0};

public:
    MsgQueue() {}

    ElementType* GetNextAddMessage()
    {
        // if we are falling behind, bail
        if (pendingSends_.load() >= QueueSize) {
            return nullptr;
        }
        auto index = (nextAdd_++) % QueueSize;
        return &queue_[index];
    }
    void CommitAdd() { ++pendingSends_; }

    bool HavePendingSends() const { return pendingSends_.load() != 0; }
    ElementType* GetNextSendMessage()
    {
        auto index = (nextSend_++) % QueueSize;
        return &queue_[index];
    }
    void CommitSend() { --pendingSends_; }
};