我正在编写一个用 pthread 实现的多线程队列。由于我根据互联网上的几个教程提出了代码,因此我想确保我的代码中没有逻辑错误:
template <typename T>
class ThreadQueue {
public:
ThreadQueue() {
pthread_mutex_init(&m_qmtx, NULL);
pthread_cond_init(&m_condv, NULL);
}
~ThreadQueue() {
pthread_mutex_lock(&m_qmtx);
m_queue.clear();
pthread_mutex_unlock(&m_qmtx);
}
void push(T t_data) {
pthread_mutex_lock(&m_qmtx);
m_queue.push_back(t_data);
pthread_mutex_unlock(&m_qmtx);
pthread_cond_signal(&m_condv);
}
T front() {
T ret;
pthread_mutex_lock(&m_qmtx);
while (m_queue.empty()) {
pthread_cond_wait(&m_condv, &m_qmtx);
}
ret = m_queue.front();
pthread_mutex_unlock(&m_qmtx);
return ret;
}
void pop() {
pthread_mutex_lock(&m_qmtx);
if (!m_queue.empty())
m_queue.pop_front();
pthread_mutex_unlock(&m_qmtx);
}
private:
std::deque<T> m_queue;
pthread_mutex_t m_qmtx;
pthread_cond_t m_condv;
};