C++11執行緒安全佇列
阿新 • • 發佈:2019-01-11
多執行緒程式設計需要實現一個執行緒安全的佇列,上鎖,避免多個執行緒同時讀寫
程式碼:
對於mutex我的理解是在同一個mutex的lock、unlock之間的程式碼不能同時執行。 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