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
#include "BlockingQueue.h"

namespace TestingNS
{
    template<class Data>
    BlockingQueue<Data>::BlockingQueue()
    {
        _closed = false;
    }

    template<class Data>
    void BlockingQueue<Data>::Close()
    {
        QMutexLocker locker(&_mutex);
        if(!_closed)
        {
            _closed = true;
            _queue.empty();
            _monitor.wakeAll()
        }
    }

    template<class Data>
    size_t BlockingQueue<Data>::Size()
    {
        QMutexLocker locker(&_mutex);
        return _queue.size();
    }
    
    template<class Data>
    void BlockingQueue<Data>::Empty()
    {
        QMutexLocker locker(&_mutex);
        _queue.empty();
        _monitor.wakeAll();
    }

    template<class Data>
    bool BlockingQueue<Data>::IsClosed()
    {
        return _closed;
    }
    
    template<class Data>
    bool BlockingQueue<Data>::Enqueue(QSharedPointer<Data> data)
    {
        QMutexLocker locker(&_mutex);

        // Make sure that the queue is not closed
        if(_closed)
        {
            return false;
        }

        _queue.push(data);
            
        // Signal all the waiting threads
        if(queue.size()==1)
        {
            _monitor.wakeAll();
        }

        return true;
    }
    
    template<class Data>
    bool BlockingQueue<Data>::TryDequeue(QSharedPointer<Data>& value, unsigned long time)
    {
        QMutexLocker locker(&_mutex);

        // Block until something goes into the queue
        // or until the queue is closed
        while(_queue.empty())
        {
            if(_closed || !_monitor.wait(&_mutex, time))
            {
                return false;
            }
        }

        // Dequeue the next item from the queue
        value = _queue.front();
        _queue.pop();
        return true;
    }
}