summaryrefslogtreecommitdiffstats
path: root/src/common/fifo_queue.h
blob: 4e80f53b4c1f26137e8b61e17f7927877785a656 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

#ifndef _FIFO_QUEUE_H_
#define _FIFO_QUEUE_H_

// a simple lockless thread-safe,
// single reader, single writer queue

#include "common/atomic.h"

namespace Common
{

template <typename T>
class FifoQueue
{
public:
    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
        // then advance the write pointer 
        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
        tmpptr->next = NULL;
        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();
    }

private:
    // stores a pointer to element
    // and a pointer to the next ElementPtr
    class ElementPtr
    {
    public:
        ElementPtr() : current(NULL), next(NULL) {}

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

}

#endif