Overte C++ Documentation
ThreadHelpers.h
1 //
2 // ThreadHelpers.h
3 //
4 // Created by Bradley Austin Davis on 2015-04-04
5 // Copyright 2015 High Fidelity, Inc.
6 //
7 // Distributed under the Apache License, Version 2.0.
8 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
9 //
10 #pragma once
11 #ifndef hifi_ThreadHelpers_h
12 #define hifi_ThreadHelpers_h
13 
14 #include <exception>
15 #include <functional>
16 
17 #include <QtCore/QMutex>
18 #include <QtCore/QMutexLocker>
19 #include <QtCore/QWaitCondition>
20 #include <QtCore/QObject>
21 #include <QtCore/QString>
22 #include <QtCore/QThread>
23 
24 template <typename L, typename F>
25 void withLock(L lock, F function) {
26  throw std::exception();
27 }
28 
29 template <typename F>
30 void withLock(QMutex& lock, F function) {
31  QMutexLocker locker(&lock);
32  function();
33 }
34 
35 void setThreadName(const std::string& name);
36 
37 void moveToNewNamedThread(QObject* object, const QString& name,
38  std::function<void(QThread*)> preStartCallback,
39  std::function<void()> startCallback,
40  QThread::Priority priority = QThread::InheritPriority);
41 
42 void moveToNewNamedThread(QObject* object, const QString& name,
43  std::function<void()> startCallback,
44  QThread::Priority priority = QThread::InheritPriority);
45 
46 void moveToNewNamedThread(QObject* object, const QString& name,
47  QThread::Priority priority = QThread::InheritPriority);
48 
49 class ConditionalGuard {
50 public:
51  void trigger() {
52  QMutexLocker locker(&_mutex);
53  _triggered = true;
54  _condition.wakeAll();
55  }
56 
57  bool wait(unsigned long time = ULONG_MAX) {
58  QMutexLocker locker(&_mutex);
59  if (!_triggered) {
60  _condition.wait(&_mutex, time);
61  }
62  return _triggered;
63  }
64 private:
65  QMutex _mutex;
66  QWaitCondition _condition;
67  bool _triggered { false };
68 };
69 
70 #endif