这是在C ++中实现线程安全队列的正确方法吗?我有多个线程不断排队和出列项目,直到某个条件发生,在此期间我“停止”队列。 感谢
#include <queue>
#include <pthread.h>
template <typename T>
class ThreadSafeQueue {
private:
std::queue<T> _queue;
pthread_mutex_t queueMutex;
pthread_cond_t emptyCondVar;
public:
ThreadSafeQueue();
bool volatile Stopped;
void Enqueue(T data);
T Dequeue();
void StopQueue();
void DestroyQueue();
};
template <typename T>
ThreadSafeQueue<T>::ThreadSafeQueue() {
pthread_mutex_init(&queueMutex, NULL);
pthread_cond_init(&emptyCondVar, NULL);
Stopped = false;
}
template <typename T>
void ThreadSafeQueue<T>::Enqueue(T data) {
pthread_mutex_lock(&queueMutex);
_queue.push(data);
pthread_cond_signal(&emptyCondVar);
pthread_mutex_unlock(&queueMutex);
}
template <typename T>
T ThreadSafeQueue<T>::Dequeue() {
pthread_mutex_lock(&queueMutex);
if (_queue.empty()) {
pthread_cond_wait(&emptyCondVar, &queueMutex);
}
if (Stopped) {
pthread_mutex_unlock(&queueMutex);
return NULL;
}
T elem = _queue.front();
_queue.pop();
pthread_mutex_unlock(&queueMutex);
return elem;
}
template <typename T>
void ThreadSafeQueue<T>::StopQueue() {
pthread_mutex_lock(&queueMutex);
Stopped = true;
pthread_cond_broadcast(&emptyCondVar);
pthread_mutex_unlock(&queueMutex);
}
template <typename T>
void ThreadSafeQueue<T>::DestroyQueue() {
pthread_mutex_lock(&queueMutex);
_queue = std::queue<T>();
pthread_mutex_unlock(&queueMutex);
}
答案 0 :(得分:1)
您的Dequeue
需要循环播放pthread_cond_wait()
:
while (_queue.empty() && !Stopped) {
pthread_cond_wait(&emptyCondVar, &queueMutex);
}