Overte C++ Documentation
GenericQueueThread.h
1 //
2 // Created by Bradley Austin Davis 2015/07/08.
3 // Copyright 2015 High Fidelity, Inc.
4 //
5 // Distributed under the Apache License, Version 2.0.
6 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
7 //
8 
9 #pragma once
10 #ifndef hifi_GenericQueueThread_h
11 #define hifi_GenericQueueThread_h
12 
13 #include <stdint.h>
14 
15 #include <QtCore/QElapsedTimer>
16 #include <QtCore/QMutex>
17 #include <QtCore/QQueue>
18 #include <QtCore/QWaitCondition>
19 
20 #include "GenericThread.h"
21 #include "NumericalConstants.h"
22 
23 template <typename T>
24 class GenericQueueThread : public GenericThread {
25 public:
26  using Queue = QQueue<T>;
27  GenericQueueThread(QObject* parent = nullptr)
28  : GenericThread() {}
29 
30  virtual ~GenericQueueThread() {}
31 
32  void queueItem(const T& t) {
33  lock();
34  queueItemInternal(t);
35  unlock();
36  _hasItems.wakeAll();
37  }
38 
39  void waitIdle(uint32_t maxWaitMs = UINT32_MAX) {
40  QElapsedTimer timer;
41  timer.start();
42 
43  // FIXME this will work as long as the thread doing the wait
44  // is the only thread which can add work to the queue.
45  // It would be better if instead we had a queue empty condition to wait on
46  // that would ensure that we get woken as soon as we're idle the very
47  // first time the queue was empty.
48  while (timer.elapsed() < maxWaitMs) {
49  lock();
50  if (!_items.size()) {
51  unlock();
52  return;
53  }
54  unlock();
55  }
56  }
57 
58  virtual bool process() override {
59  lock();
60  if (!_items.size()) {
61  unlock();
62  _hasItemsMutex.lock();
63  _hasItems.wait(&_hasItemsMutex, getMaxWait());
64  _hasItemsMutex.unlock();
65  } else {
66  unlock();
67  }
68 
69  lock();
70  if (!_items.size()) {
71  unlock();
72  return isStillRunning();
73  }
74 
75  Queue processItems;
76  processItems.swap(_items);
77  unlock();
78  return processQueueItems(processItems);
79  }
80 
81 protected:
82  virtual void queueItemInternal(const T& t) {
83  _items.push_back(t);
84  }
85 
86  virtual uint32_t getMaxWait() {
87  return MSECS_PER_SECOND;
88  }
89 
90 
91 
92  virtual bool processQueueItems(const Queue& items) = 0;
93 
94  Queue _items;
95  QWaitCondition _hasItems;
96  QMutex _hasItemsMutex;
97 };
98 
99 #endif // hifi_GenericQueueThread_h
Definition: GenericThread.h:23
virtual bool process()=0
Override this function to do whatever your class actually does, return false to exit thread early.
void lock()
Locks all the resources of the thread.
Definition: GenericThread.h:56
void unlock()
Unlocks all the resources of the thread.
Definition: GenericThread.h:59