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
4#ifndef QWINDOWSTHREADPOOLRUNNER_H
5#define QWINDOWSTHREADPOOLRUNNER_H
6
7#include <QtCore/qmutex.h>
8#include <QtCore/qrunnable.h>
9#include <QtCore/qthreadpool.h>
10#include <QtCore/qwaitcondition.h>
11
12QT_BEGIN_NAMESPACE
13
14/*!
15 \class QWindowsThreadPoolRunner
16 \brief Runs a task in the global instance of QThreadPool
17
18 QThreadPool does not provide a method to wait on a single task, so this needs
19 to be done by using QWaitCondition/QMutex.
20
21 \internal
22*/
23class QWindowsThreadPoolRunner
24{
25 Q_DISABLE_COPY_MOVE(QWindowsThreadPoolRunner)
26
27#if QT_CONFIG(thread)
28 template <class RunnableFunction> // nested class implementing QRunnable to execute a function.
29 class Runnable : public QRunnable
30 {
31 public:
32 explicit Runnable(QMutex *m, QWaitCondition *c, RunnableFunction f)
33 : m_mutex(m), m_condition(c), m_function(f) {}
34
35 void run() override
36 {
37 m_function();
38 m_mutex->lock();
39 m_condition->wakeAll();
40 m_mutex->unlock();
41 }
42
43 private:
44 QMutex *m_mutex;
45 QWaitCondition *m_condition;
46 RunnableFunction m_function;
47 }; // class Runnable
48
49public:
50 QWindowsThreadPoolRunner() {}
51
52 template <class Function>
53 bool run(Function f, unsigned long timeOutMSecs = 5000)
54 {
55 QThreadPool *pool = QThreadPool::globalInstance();
56 Q_ASSERT(pool);
57 Runnable<Function> *runnable = new Runnable<Function>(&m_mutex, &m_condition, f);
58 m_mutex.lock();
59 pool->start(runnable);
60 const bool ok = m_condition.wait(&m_mutex, timeOutMSecs);
61 m_mutex.unlock();
62 if (!ok)
63 pool->cancel(runnable);
64 return ok;
65 }
66
67private:
68 QMutex m_mutex;
69 QWaitCondition m_condition;
70#else // QT_CONFIG(thread)
71public:
72 QWindowsThreadPoolRunner() {}
73
74 template <class Function>
75 bool run(Function f, unsigned long /* timeOutMSecs */ = 5000)
76 {
77 f();
78 return true;
79 }
80#endif // QT_CONFIG(thread)
81};
82
83QT_END_NAMESPACE
84
85#endif // QWINDOWSTHREADPOOLRUNNER_H