rpcs3/Utilities/SQueue.h

145 lines
1.7 KiB
C
Raw Normal View History

2014-02-24 04:00:42 +04:00
#pragma once
2014-08-23 18:51:51 +04:00
#include "Utilities/SMutex.h"
2014-02-24 04:00:42 +04:00
template<typename T, u32 SQSize = 666>
class SQueue
{
std::mutex m_mutex;
2014-02-24 04:00:42 +04:00
u32 m_pos;
u32 m_count;
T m_data[SQSize];
public:
SQueue()
: m_pos(0)
, m_count(0)
{
}
const u32 GetSize() const
{
return SQSize;
}
2014-03-06 15:50:45 +04:00
bool Push(const T& data)
2014-02-24 04:00:42 +04:00
{
while (true)
{
if (m_count >= SQSize)
{
2014-03-03 03:02:42 +04:00
if (Emu.IsStopped())
{
return false;
}
2014-06-20 23:57:28 +04:00
SM_Sleep();
2014-02-24 04:00:42 +04:00
continue;
}
{
std::lock_guard<std::mutex> lock(m_mutex);
2014-02-24 04:00:42 +04:00
if (m_count >= SQSize) continue;
m_data[(m_pos + m_count++) % SQSize] = data;
return true;
}
}
}
bool Pop(T& data)
{
while (true)
{
if (!m_count)
{
2014-03-03 03:02:42 +04:00
if (Emu.IsStopped())
{
return false;
}
2014-06-20 23:57:28 +04:00
SM_Sleep();
2014-02-24 04:00:42 +04:00
continue;
}
{
std::lock_guard<std::mutex> lock(m_mutex);
2014-02-24 04:00:42 +04:00
if (!m_count) continue;
data = m_data[m_pos];
m_pos = (m_pos + 1) % SQSize;
m_count--;
return true;
}
}
}
2014-06-29 07:21:57 +04:00
u32 GetCount()
2014-02-24 04:00:42 +04:00
{
2014-06-29 07:21:57 +04:00
std::lock_guard<std::mutex> lock(m_mutex);
2014-02-24 04:00:42 +04:00
return m_count;
}
2014-06-29 07:21:57 +04:00
u32 GetCountUnsafe()
2014-02-24 04:00:42 +04:00
{
2014-06-29 07:21:57 +04:00
return m_count;
}
bool IsEmpty()
{
std::lock_guard<std::mutex> lock(m_mutex);
2014-02-24 04:00:42 +04:00
return !m_count;
}
void Clear()
{
std::lock_guard<std::mutex> lock(m_mutex);
2014-02-24 04:00:42 +04:00
m_count = 0;
}
2014-03-03 03:02:42 +04:00
T& Peek(u32 pos = 0)
{
2014-03-22 05:08:25 +04:00
while (true)
{
2014-06-29 07:21:57 +04:00
if (m_count <= pos)
2014-03-22 05:08:25 +04:00
{
if (Emu.IsStopped())
{
break;
}
2014-06-20 23:57:28 +04:00
SM_Sleep();
2014-03-22 05:08:25 +04:00
continue;
}
{
std::lock_guard<std::mutex> lock(m_mutex);
2014-06-29 07:21:57 +04:00
if (m_count > pos)
2014-06-20 23:57:28 +04:00
{
break;
}
2014-03-22 05:08:25 +04:00
}
}
2014-03-03 03:02:42 +04:00
return m_data[(m_pos + pos) % SQSize];
}
2014-06-29 07:21:57 +04:00
2014-07-01 20:04:58 +04:00
T& PeekIfExist(u32 pos = 0)
2014-06-29 07:21:57 +04:00
{
2014-07-01 20:04:58 +04:00
static T def_value;
2014-06-29 07:21:57 +04:00
std::lock_guard<std::mutex> lock(m_mutex);
if (m_count <= pos)
{
2014-07-01 20:04:58 +04:00
return def_value;
2014-06-29 07:21:57 +04:00
}
else
{
return m_data[(m_pos + pos) % SQSize];
}
}
2014-03-06 15:50:45 +04:00
};