• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * GStreamer
3  * Copyright (C) 2009 Andrey Nechypurenko <andreynech@gmail.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 
21 #ifndef __ASYNCQUEUE_H
22 #define __ASYNCQUEUE_H
23 
24 #include <QMutex>
25 #include <QWaitCondition>
26 #include <QList>
27 
28 /**
29  * This is the thread safe implementation of the Queue.  It can be
30  * used in classical producers/consumers multithreaded scenario.  The
31  * template parameter is the class which can be put/get to/from the
32  * queue.
33  */
34 template<class T>
35 class AsyncQueue
36 {
37 public:
AsyncQueue()38     AsyncQueue() : waitingReaders(0) {}
39 
size()40     int size()
41     {
42         QMutexLocker locker(&mutex);
43         return this->buffer.size();
44     }
45 
put(const T & item)46     void put(const T& item)
47     {
48         QMutexLocker locker(&mutex);
49         this->buffer.push_back(item);
50         if(this->waitingReaders)
51             this->bufferIsNotEmpty.wakeOne();
52     }
53 
get()54     T get()
55     {
56         QMutexLocker locker(&mutex);
57         while(this->buffer.size() == 0)
58         {
59             ++(this->waitingReaders);
60             this->bufferIsNotEmpty.wait(&mutex);
61             --(this->waitingReaders);
62         }
63         T item = this->buffer.front();
64         this->buffer.pop_front();
65         return item;
66     }
67 
68 private:
69     typedef QList<T> Container;
70     QMutex mutex;
71     QWaitCondition bufferIsNotEmpty;
72     Container buffer;
73     short waitingReaders;
74 };
75 
76 
77 #endif // __ASYNCQUEUE_H
78