C++ Patterns - Thread-safe Queue
The below class implements a thread-safe queue with a condition variable.
c++
#ifndef _THREADSAFE_QUEUE_H_
#define _THREADSAFE_QUEUE_H_
#include <queue>
#include <condition_variable>
#include <mutex>
template <class T> class ThreadsafeQueue {
public:
ThreadsafeQueue(void) : queue(), mutex(), condition() {}
~ThreadsafeQueue(void) {}
void enqueue(T t) {
std::lock_guard<std::mutex> lock(mutex);
queue.push(t);
condition.notify_one();
}
T dequeue(void) {
std::unique_lock<std::mutex> lock(mutex);
while (queue.empty()) {
condition.wait(lock);
}
T val = queue.front();
queue.pop();
return val;
}
int empty() { return queue.empty(); }
private:
std::queue<T> queue;
mutable std::mutex mutex;
std::condition_variable condition;
};
#endif // _THREADSAFE_QUEUE_H
#ifndef _THREADSAFE_QUEUE_H_
#define _THREADSAFE_QUEUE_H_
#include <queue>
#include <condition_variable>
#include <mutex>
template <class T> class ThreadsafeQueue {
public:
ThreadsafeQueue(void) : queue(), mutex(), condition() {}
~ThreadsafeQueue(void) {}
void enqueue(T t) {
std::lock_guard<std::mutex> lock(mutex);
queue.push(t);
condition.notify_one();
}
T dequeue(void) {
std::unique_lock<std::mutex> lock(mutex);
while (queue.empty()) {
condition.wait(lock);
}
T val = queue.front();
queue.pop();
return val;
}
int empty() { return queue.empty(); }
private:
std::queue<T> queue;
mutable std::mutex mutex;
std::condition_variable condition;
};
#endif // _THREADSAFE_QUEUE_H