多线程编程需要实现一个线程安全的队列,上锁,避免多个线程同时读写
代码:
/**
* 线程安全的队列
*/
#ifndef __THREAD_SAFE_QUEUE__
#define __THREAD_SAFE_QUEUE__
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
template <class T>
class thread_safe_queue
{
private:
mutable mutex mut; //锁
queue<T> data_queue; //队列
condition_variable data_cond; //条件变量
public:
//构造函数
thread_safe_queue();
thread_safe_queue &operator=(const thread_safe_queue&)=delete;
//可以多传递一个额外的条件
bool wait_and_pop(T &value,atomic_bool &bl);
bool try_pop(T &value);
void push(T new_value);
bool empty() const;
void notify_all()
{
data_cond.notify_all();
}
};
template <class T>
thread_safe_queue<T>::thread_safe_queue(){}
template <class T>
bool thread_safe_queue<T>::empty() const
{
lock_guard<mutex> lock(mut);
return data_queue.empty();
}
template <class T>
void thread_safe_queue<T>::push(T new_value)
{
lock_guard<mutex> lock(mut);
data_queue.push(new_value);
data_cond.notify_one();
}
template <class T>
bool thread_safe_queue<T>::wait_and_pop(T &value,atomic_bool &bl)
{
unique_lock<mutex> lock(mut);
//避免队列为空时一直等待
data_cond.wait(lock,[this,&bl](){return (!this->data_queue.empty())||bl; });
if(bl&&data_queue.empty())
return false;
value=data_queue.front();
data_queue.pop();
return true;
}
template<class T>
bool thread_safe_queue<T>::try_pop(T &value)
{
lock_guard<mutex> lock(mut);
if(empty())
return false;
value=data_queue.front();
data_queue.pop();
return true;
}
#endif
对于mutex我的理解是在同一个mutex的lock、unlock之间的代码不能同时运行。