#ifndef _BASE_QUEUE_H_
#define _BASE_QUEUE_H_
#include <queue>
#include <mutex>
class BaseQueue
{
public:
BaseQueue();
~BaseQueue();
int PutEmptyBuf(void *pObj);
int GetEmptyBuf(void **pObj);
int PutFullBuf(void *pObj);
int GetFullBuf(void **pObj);
int GetFullBufCount(int *pCount);
private:
std::queue<void*> m_emptyQue;
std::queue<void*> m_fullQue;
std::mutex m_mutex;
};
#endif
#include "base_queue.h"
BaseQueue::BaseQueue()
{
}
BaseQueue::~BaseQueue()
{
}
int BaseQueue::PutEmptyBuf(void *pObj)
{
if (NULL == pObj)
{
return -1;
}
std::lock_guard<std::mutex> lx(m_mutex);
m_emptyQue.push(pObj);
return 0;
}
int BaseQueue::GetEmptyBuf(void **pObj)
{
std::lock_guard<std::mutex> lx(m_mutex);
if (m_emptyQue.size() == 0)
{
return -1;
}
*pObj = m_emptyQue.front();
m_emptyQue.pop();
return 0;
}
int BaseQueue::PutFullBuf(void *pObj)
{
if (NULL == pObj)
{
return -1;
}
std::lock_guard<std::mutex> lx(m_mutex);
m_fullQue.push(pObj);
return 0;
}
int BaseQueue::GetFullBuf(void **pObj)
{
std::lock_guard<std::mutex> lx(m_mutex);
if (m_fullQue.size() == 0)
{
return -1;
}
*pObj = m_fullQue.front();
m_fullQue.pop();
return 0;
}
int BaseQueue::GetFullBufCount(int *pCount)
{
std::lock_guard<std::mutex> lx(m_mutex);
if (NULL == pCount || m_fullQue.size() == 0)
{
return -1;
}
*pCount = m_fullQue.size();
return 0;
}
使用方式:
#include <iostream>
using namespace std;
#include "base_queue.h"
//流程 初始化向空的PutEmptyBuf
//使用:GetEmptyBuf ->PutFullBuf ->GetFullBuf ->PutEmptyBuf
int main()
{
int nRet = 0;
BaseQueue qe;
int *pA = new int;
memset(pA, 0, sizeof(int));
qe.PutEmptyBuf(pA);
void *pTmp1 = NULL;
qe.GetEmptyBuf(&pTmp1);
*(int*)pTmp1 = 1;
qe.PutFullBuf(pTmp1);
int nCount = 0;
qe.GetFullBufCount(&nCount);
void *pTmp11 = NULL;
nRet = qe.GetFullBuf(&pTmp11);
if (nRet != 0)
{
//error
}
int value = *(int*)pTmp11;
qe.PutEmptyBuf(pTmp11);
return 0;
}