C++ 11 实现高性能队列,参考DX 3D 12 游戏绘制队列部分设计方式。
测试代码可以从文章中下载:
直接干货:
using test_buffer = std::basic_string<unsigned char, std::char_traits<unsigned char>, std::allocator<unsigned char>>;
也可直接使用std::string
以上 test_buffer 代码定义只是希望给新手提供更多的字符串操作方式用例。
int main()
{
PackageCache<test_buffer> m_cacheDatas;
std::future<void> testThread;
testThread = std::async(std::launch::async, [&]
{
for (int i = 0; i < 13000; i++)
{
char buff[8] = { 0 };
sprintf_s(buff, "%d", i);
m_cacheDatas.addData(test_buffer(buff));
if (i > 12000)
Sleep(1);
}
m_cacheDatas.addData(test_buffer("-1"));
});
Sleep(100);
test_buffer temp;
while (true)
{
if (m_cacheDatas.getPackage(temp))
{
printf("recv: %s\n", temp.c_str());
if (temp == "-1")
break;
}
else
{
Sleep(10);
}
}
testThread.wait();
return 0;
}
模版类
#pragma once
#include <string>
#include <queue>
#include <mutex>
template<class T>
class PackageCache final
{
public:
void addData(const T& data)
{
m_mutex.lock();
m_queueBackCache.emplace(std::move(data));
m_mutex.unlock();
}
inline int getLen() { return (int)m_queueBackCache.size(); }
bool getPackage(T& ret)
{
if (m_queueFrontCache.size() <= 0)
moveData(m_queueFrontCache);
bool bRet = false;
if (m_queueFrontCache.size() > 0)
{
bRet = true;
ret = std::move(m_queueFrontCache.front());
m_queueFrontCache.pop();
}
return bRet;
}
template<class T1>
void clear()
{
std::queue<T1> temp1;
std::queue<T1> temp2;
m_mutex.lock();
m_queueBackCache = std::move(temp1);
m_queueFrontCache = std::move(temp1);
m_mutex.unlock();
}
protected:
bool moveData(std::queue<T>& ret)
{
bool bRet = false;
m_mutex.lock();
if (m_queueBackCache.size() > 0)
{
ret = std::move(m_queueBackCache);
bRet = true;
}
m_mutex.unlock();
return bRet;
}
protected:
std::queue<T> m_queueBackCache;
std::queue<T> m_queueFrontCache;
std::mutex m_mutex;
};