KanoopCommonQt 2.1.1
Kanoop foundational Qt utility library
Loading...
Searching...
No Matches
lockingqueue.h
1/**
2 * LockingQueue
3 *
4 * Thread-safe Multi-producer Multi-consumer blocking queue
5 *
6 * Stephen Punak, July 08 2019
7 */
8#ifndef LOCKINGQUEUE_H
9#define LOCKINGQUEUE_H
10
11#include <QList>
12#include <QWaitCondition>
13#include <QMutex>
14
15/**
16 * @brief Thread-safe, blocking multi-producer multi-consumer queue.
17 *
18 * @tparam T Element type stored in the queue
19 */
20template <class T>
21class LockingQueue : public QList<T>
22{
23public:
24 /**
25 * @brief Remove and return the front element, blocking until one is available or timeout elapses.
26 * @param waitTimeMs Maximum time to wait in milliseconds
27 * @param success Output set to true if an element was dequeued, false on timeout
28 * @return Dequeued element, or a default-constructed T on timeout
29 */
30 T dequeue(quint32 waitTimeMs, bool& success)
31 {
32 T result = T();
33 success = false;
34
35 _queueLock.lock(); // don't allow anyone to add until we check the count
36
37 if(this->count() > 0)
38 {
39 result = this->takeFirst();
40 success = true;
41 _queueLock.unlock();
42 }
43 else
44 {
45 if(_condition.wait(&_queueLock, quint32(waitTimeMs)))
46 {
47 if(this->count() > 0)
48 {
49 result = this->takeFirst();
50 success = true;
51 }
52 }
53 _queueLock.unlock();
54 }
55 return result;
56 }
57
58 /**
59 * @brief Append an element to the back of the queue and wake one waiting consumer.
60 * @param t Element to enqueue
61 */
62 void enqueue(const T& t)
63 {
64 _queueLock.lock();
65 this->append(t);
66 _queueLock.unlock();
67 _condition.notify_one();
68 }
69
70private:
71 QWaitCondition _condition;
72 QMutex _queueLock;
73};
74
75#endif // LOCKINGQUEUE_H
LockingQueue.
void enqueue(const T &t)
Append an element to the back of the queue and wake one waiting consumer.
T dequeue(quint32 waitTimeMs, bool &success)
Remove and return the front element, blocking until one is available or timeout elapses.