头文件:
#include <mutex> #include <queue> #include <functional> #include <future> #include <thread> #include <utility> #include <vector> #include <condition_variable> class SafeQueue { private: std::queue<void *> m_queue; //利用模板函数构造队列 mutable std::mutex m_mutex; // 访问互斥信号量 mutable std::condition_variable data_cond; int m_max_size = 5; public: SafeQueue() ; SafeQueue(int size) ; SafeQueue(SafeQueue &&other); ~SafeQueue(); bool isEmpty(); int GetSize(); bool PushData(void *data); bool PopData(void *data); void * wait_and_pop(); };
源文件:
#pragma once #include <queue> #include <mutex> #include <condition_variable> #include <initializer_list> #include "safequeue.h" #include <iostream> using namespace std; SafeQueue::SafeQueue() { cout<<__FUNCTION__; } SafeQueue::SafeQueue(int size) { m_max_size = size; cout<<__FUNCTION__<<endl; } SafeQueue::SafeQueue(SafeQueue &&other) { } SafeQueue::~SafeQueue() { std::cout<<__FUNCTION__<<endl; } bool SafeQueue::isEmpty() { std::unique_lock<std::mutex> lock(m_mutex); return m_queue.empty(); } bool SafeQueue::PushData(void *data) { std::unique_lock<std::mutex> lock(m_mutex); if(m_queue.size() == m_max_size) { return false; } m_queue.emplace(data); data_cond.notify_one(); return true; } bool SafeQueue::PopData(void *data) { std::unique_lock<std::mutex> lock(m_mutex); if (m_queue.empty()) return false; data = std::move(m_queue.front()); m_queue.pop(); return true; } int SafeQueue::GetSize() { std::unique_lock<std::mutex> lock(m_mutex); return m_queue.size(); } void * SafeQueue::wait_and_pop() { std::unique_lock<std::mutex> lock(m_mutex); data_cond.wait(lock,[this]{return !this->m_queue.empty();}); if(m_queue.size() == 0) { return NULL; } else { auto value =std::move(m_queue.front()); m_queue.pop(); return value; } }