Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindowsthreadpoolrunner.h
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#ifndef QWINDOWSTHREADPOOLRUNNER_H
6#define QWINDOWSTHREADPOOLRUNNER_H
7
8#include <QtCore/qmutex.h>
9#include <QtCore/qrunnable.h>
10#include <QtCore/qthreadpool.h>
11#include <QtCore/qwaitcondition.h>
12
13QT_BEGIN_NAMESPACE
14
15/*!
16 \class QWindowsThreadPoolRunner
17 \brief Runs a task in the global instance of QThreadPool
18
19 QThreadPool does not provide a method to wait on a single task, so this needs
20 to be done by using QWaitCondition/QMutex.
21
22 \internal
23*/
24class QWindowsThreadPoolRunner
25{
26 Q_DISABLE_COPY_MOVE(QWindowsThreadPoolRunner)
27
28#if QT_CONFIG(thread)
29 template <class RunnableFunction> // nested class implementing QRunnable to execute a function.
30 class Runnable : public QRunnable
31 {
32 public:
33 explicit Runnable(QMutex *m, QWaitCondition *c, RunnableFunction f)
34 : m_mutex(m), m_condition(c), m_function(f) {}
35
36 void run() override
37 {
38 m_function();
39 m_mutex->lock();
40 m_condition->wakeAll();
41 m_mutex->unlock();
42 }
43
44 private:
45 QMutex *m_mutex;
46 QWaitCondition *m_condition;
47 RunnableFunction m_function;
48 }; // class Runnable
49
50public:
51 QWindowsThreadPoolRunner() {}
52
53 template <class Function>
54 bool run(Function f, unsigned long timeOutMSecs = 5000)
55 {
56 QThreadPool *pool = QThreadPool::globalInstance();
57 Q_ASSERT(pool);
58 Runnable<Function> *runnable = new Runnable<Function>(&m_mutex, &m_condition, f);
59 m_mutex.lock();
60 pool->start(runnable);
61 const bool ok = m_condition.wait(&m_mutex, timeOutMSecs);
62 m_mutex.unlock();
63 if (!ok)
64 pool->cancel(runnable);
65 return ok;
66 }
67
68private:
69 QMutex m_mutex;
70 QWaitCondition m_condition;
71#else // QT_CONFIG(thread)
72public:
73 QWindowsThreadPoolRunner() {}
74
75 template <class Function>
76 bool run(Function f, unsigned long /* timeOutMSecs */ = 5000)
77 {
78 f();
79 return true;
80 }
81#endif // QT_CONFIG(thread)
82};
83
84QT_END_NAMESPACE
85
86#endif // QWINDOWSTHREADPOOLRUNNER_H