2014-08-17 19:45:50 +02:00
|
|
|
#pragma once
|
2013-09-05 02:17:46 +02:00
|
|
|
|
|
|
|
// a simple lockless thread-safe,
|
|
|
|
// single reader, single writer queue
|
|
|
|
|
2014-04-09 02:15:08 +02:00
|
|
|
#include "common/atomic.h"
|
2013-09-05 02:17:46 +02:00
|
|
|
|
|
|
|
namespace Common
|
|
|
|
{
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
class FifoQueue
|
|
|
|
{
|
|
|
|
public:
|
2014-04-02 00:20:08 +02:00
|
|
|
FifoQueue() : m_size(0)
|
|
|
|
{
|
|
|
|
m_write_ptr = m_read_ptr = new ElementPtr();
|
|
|
|
}
|
|
|
|
|
|
|
|
~FifoQueue()
|
|
|
|
{
|
|
|
|
// this will empty out the whole queue
|
|
|
|
delete m_read_ptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
u32 Size() const
|
|
|
|
{
|
|
|
|
return m_size;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Empty() const
|
|
|
|
{
|
|
|
|
//return (m_read_ptr == m_write_ptr);
|
|
|
|
return (0 == m_size);
|
|
|
|
}
|
|
|
|
|
|
|
|
T& Front() const
|
|
|
|
{
|
|
|
|
return *m_read_ptr->current;
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename Arg>
|
|
|
|
void Push(Arg&& t)
|
|
|
|
{
|
|
|
|
// create the element, add it to the queue
|
|
|
|
m_write_ptr->current = new T(std::forward<Arg>(t));
|
|
|
|
// set the next pointer to a new element ptr
|
2014-11-19 09:49:13 +01:00
|
|
|
// then advance the write pointer
|
2014-04-02 00:20:08 +02:00
|
|
|
m_write_ptr = m_write_ptr->next = new ElementPtr();
|
|
|
|
Common::AtomicIncrement(m_size);
|
|
|
|
}
|
|
|
|
|
|
|
|
void Pop()
|
|
|
|
{
|
|
|
|
Common::AtomicDecrement(m_size);
|
|
|
|
ElementPtr *const tmpptr = m_read_ptr;
|
|
|
|
// advance the read pointer
|
|
|
|
m_read_ptr = m_read_ptr->next;
|
|
|
|
// set the next element to NULL to stop the recursive deletion
|
2014-12-03 19:57:57 +01:00
|
|
|
tmpptr->next = nullptr;
|
2014-04-02 00:20:08 +02:00
|
|
|
delete tmpptr; // this also deletes the element
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Pop(T& t)
|
|
|
|
{
|
|
|
|
if (Empty())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
t = std::move(Front());
|
|
|
|
Pop();
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// not thread-safe
|
|
|
|
void Clear()
|
|
|
|
{
|
|
|
|
m_size = 0;
|
|
|
|
delete m_read_ptr;
|
|
|
|
m_write_ptr = m_read_ptr = new ElementPtr();
|
|
|
|
}
|
2013-09-05 02:17:46 +02:00
|
|
|
|
|
|
|
private:
|
2014-04-02 00:20:08 +02:00
|
|
|
// stores a pointer to element
|
|
|
|
// and a pointer to the next ElementPtr
|
|
|
|
class ElementPtr
|
|
|
|
{
|
|
|
|
public:
|
2014-12-03 19:57:57 +01:00
|
|
|
ElementPtr() : current(nullptr), next(nullptr) {}
|
2014-04-02 00:20:08 +02:00
|
|
|
|
|
|
|
~ElementPtr()
|
|
|
|
{
|
|
|
|
if (current)
|
|
|
|
{
|
|
|
|
delete current;
|
|
|
|
// recusion ftw
|
|
|
|
if (next)
|
|
|
|
delete next;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
T *volatile current;
|
|
|
|
ElementPtr *volatile next;
|
|
|
|
};
|
|
|
|
|
|
|
|
ElementPtr *volatile m_write_ptr;
|
|
|
|
ElementPtr *volatile m_read_ptr;
|
|
|
|
volatile u32 m_size;
|
2013-09-05 02:17:46 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
}
|