Date: 2025may13
Language: C++
Q. C++: make std::queue<> thread-safe
A. Here is a minimal implementation
File safequeue.h
#ifndef SAFE_QUEUE_H
#define SAFE_QUEUE_H
#include <stdexcept>
#include <mutex>
#include <queue>
template <typename T>
class SafeQueue {
std::mutex m_mutex;
std::queue<T> m_queue;
public:
void push(const T ent) {
const std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(ent);
}
T pop() {
const std::lock_guard<std::mutex> lock(m_mutex);
if (m_queue.empty()) {
throw std::out_of_range("Queue is empty");
}
const T ent = m_queue.front();
m_queue.pop();
return ent;
}
// We don't implement size() or empty. Users can call pop() and check
// for an exception
};
#endif
Example Use:
#include "safequeue.h"
void exampleUse() {
SafeQueue<std::string> myQueue;
myQueue.push("one");
myQueue.push("two");
myQueue.push("three");
}