C++11:基於std::queue和std::mutex構建一個線程安全的隊列
C++中的模板std::queue提供了一個隊列容器,但這個容器並不是線程安全的,如果在多線程環境下使用隊列,它是不能直接拿來用的。
基於它做一個線程安全的隊列也並不復雜。基本的原理就是用std::mutext信號量對std::queue進行訪問控制,以保證任何一個線程都是獨占式訪問,下面是完整的代碼。
/* * threadsafe_queue.h * * Created on: 2016年7月26日 * Author: guyadong */ #ifndef COMMON_SOURCE_CPP_THREADSAFE_QUEUE_H_ #define COMMON_SOURCE_CPP_THREADSAFE_QUEUE_H_ #include <queue> #include <mutex> #include <condition_variable> #include <initializer_list> namespace gdface { inline namespace mt{ /* * 線程安全隊列 * T為隊列元素類型 * 因為有std::mutex和std::condition_variable類成員,所以此類不支持復制構造函數也不支持賦值操作符(=) * */ template<typename T> class threadsafe_queue{ private: // data_queue訪問信號量 mutable std::mutex mut; mutable std::condition_variable data_cond; using queue_type = std::queue<T>; queue_type data_queue; public: using value_type= typename queue_type::value_type; using container_type = typename queue_type::container_type; threadsafe_queue()=default; threadsafe_queue(const threadsafe_queue&)=delete; threadsafe_queue& operator=(const threadsafe_queue&)=delete; /* * 使用迭代器為參數的構造函數,適用所有容器對象 * */ template<typename _InputIterator> threadsafe_queue(_InputIterator first, _InputIterator last){ for(auto itor=first;itor!=last;++itor){ data_queue.push(*itor); } } explicit threadsafe_queue(const container_type &c):data_queue(c){} /* * 使用初始化列表為參數的構造函數 * */ threadsafe_queue(std::initializer_list<value_type> list):threadsafe_queue(list.begin(),list.end()){ } /* * 將元素加入隊列 * */ void push(const value_type &new_value){ std::lock_guard<std::mutex>lk(mut); data_queue.push(std::move(new_value)); data_cond.notify_one(); } /* * 從隊列中彈出一個元素,如果隊列為空就阻塞 * */ value_type wait_and_pop(){ std::unique_lock<std::mutex>lk(mut); data_cond.wait(lk,[this]{return !this->data_queue.empty();}); auto value=std::move(data_queue.front()); data_queue.pop(); return value; } /* * 從隊列中彈出一個元素,如果隊列為空返回false * */ bool try_pop(value_type& value){ std::lock_guard<std::mutex>lk(mut); if(data_queue.empty()) return false; value=std::move(data_queue.front()); data_queue.pop(); return true; } /* * 返回隊列是否為空 * */ auto empty() const->decltype(data_queue.empty()) { std::lock_guard<std::mutex>lk(mut); return data_queue.empty(); } /* * 返回隊列中元素數個 * */ auto size() const->decltype(data_queue.size()){ std::lock_guard<std::mutex>lk(mut); return data_queue.size(); } }; /* threadsafe_queue */ }/* namespace mt */ }/* namespace gdface */ #endif /* COMMON_SOURCE_CPP_THREADSAFE_QUEUE_H_ */
這里只實現了阻塞式的pop函數wait_and_pop
,你也可以根據自己的需要對代碼進行適當的改造,以符合自己的需求。
(C++11風格代碼,在VS2015和gcc5.2.0下編譯通過)
因為有std::mutex和std::condition_variable類成員,所以此類不支持復制構造函數也不支持賦值操作符(=)