All Notes

MPMC Queue

Last updated

Jan 10, 2026

In the impl with LOCKS it will be similar i guess to spsc? Wonder if any obvious optimisations can be made since lots of contention could be present due to loads of Ps/Cs

#include <mutex>
#include <condition_variable>
#include <optional>
#include <vector>

template<typename T>
class LockedQueue {
std::vector<T> buf;
size_t head = 0, tail = 0, sz = 0;
std::mutex mtx;
std::condition_variable cv;

public:
explicit LockedQueue(size_t cap) : buf(cap) {}

bool push(T val) {
std::unique_lock lock(mtx);
if (sz == buf.size()) return false;
buf[tail] = std::move(val);
tail = (tail + 1) % buf.size();
++sz;
cv.notify_one();
return true;
}

std::optional<T> pop() {
std::unique_lock lock(mtx);
cv.wait(lock, [this] { return sz > 0; });
T val = std::move(buf[head]);
head = (head + 1) % buf.size();
--sz;
return val;
}
};

Other notes about Concurrency and/or C++