C/C++教程

C++ 11 利用std::queue创建安全队列 等待队列

本文主要是介绍C++ 11 利用std::queue创建安全队列 等待队列,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

头文件:

#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;
	}
}

这篇关于C++ 11 利用std::queue创建安全队列 等待队列的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!