C++11线程安全队列
2017-05-22 18:37
323 查看
多线程编程需要实现一个线程安全的队列,上锁,避免多个线程同时读写
代码:
condition_variable:线程之间同步的一种方式,通过notify_one --> wait、ontify_all-->wait配合使用
代码:
/** * 线程安全的队列 */ #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之间的代码不能同时运行。
condition_variable:线程之间同步的一种方式,通过notify_one --> wait、ontify_all-->wait配合使用
相关文章推荐
- C++11 使用 unique_lock,lock_guard,condition_variable, lambda表达式实现线程安全队列
- C++11线程安全队列和安全栈
- C++11:基于std::queue和std::mutex构建一个线程安全的队列
- 用c++11写的一个线程安全的队列
- c++11baohan线程安全的队列
- c++11多线程编程---线程安全队列
- c++11 线程安全的队列实现
- c++11线程安全的队列的类的定义
- 多线程下面日志输出-线程安全-消息队列循环输出
- java多线程 --ConcurrentLinkedQueue 非阻塞 线程安全队列
- python实现线程安全队列
- 高效的线程安全队列ConcurrentQueue<T>(上)
- 用C++实现单例模式3——如何在不使用锁和C++11的情况下,用C++实现线程安全的Singleton
- delphi非常简单的线程安全队列
- linux 线程安全队列
- C++11 可复用线程任务队列
- java实现线程安全的队列
- Linux多线程系列-2-条件变量的使用(线程安全队列的实现)
- 多写多读-线程安全队列1
- 单例模式实现 线程安全的队列 处理