1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtCore module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40#ifndef QMUTEX_H
41#define QMUTEX_H
42
43#include <QtCore/qglobal.h>
44#include <QtCore/qatomic.h>
45#include <new>
46
47#if __has_include(<chrono>)
48# include <chrono>
49# include <limits>
50#endif
51
52class tst_QMutex;
53
54QT_BEGIN_NAMESPACE
55
56
57#if QT_CONFIG(thread) || defined(Q_CLANG_QDOC)
58
59#ifdef Q_OS_LINUX
60# define QT_MUTEX_LOCK_NOEXCEPT noexcept
61#else
62# define QT_MUTEX_LOCK_NOEXCEPT
63#endif
64
65class QMutex;
66class QRecursiveMutex;
67class QMutexData;
68
69class Q_CORE_EXPORT QBasicMutex
70{
71public:
72#ifdef Q_COMPILER_CONSTEXPR
73 constexpr QBasicMutex()
74 : d_ptr(nullptr)
75 {}
76#endif
77
78 // BasicLockable concept
79 inline void lock() QT_MUTEX_LOCK_NOEXCEPT {
80 if (!fastTryLock())
81 lockInternal();
82 }
83
84 // BasicLockable concept
85 inline void unlock() noexcept {
86 Q_ASSERT(d_ptr.loadRelaxed()); //mutex must be locked
87 if (!fastTryUnlock())
88 unlockInternal();
89 }
90
91 bool tryLock() noexcept {
92 return fastTryLock();
93 }
94
95 // Lockable concept
96 bool try_lock() noexcept { return tryLock(); }
97
98 bool isRecursive() noexcept; //### Qt6: remove me
99 bool isRecursive() const noexcept;
100
101private:
102 inline bool fastTryLock() noexcept {
103 return d_ptr.testAndSetAcquire(expectedValue: nullptr, newValue: dummyLocked());
104 }
105 inline bool fastTryUnlock() noexcept {
106 return d_ptr.testAndSetRelease(expectedValue: dummyLocked(), newValue: nullptr);
107 }
108 inline bool fastTryLock(QMutexData *&current) noexcept {
109 return d_ptr.testAndSetAcquire(expectedValue: nullptr, newValue: dummyLocked(), currentValue&: current);
110 }
111 inline bool fastTryUnlock(QMutexData *&current) noexcept {
112 return d_ptr.testAndSetRelease(expectedValue: dummyLocked(), newValue: nullptr, currentValue&: current);
113 }
114
115 void lockInternal() QT_MUTEX_LOCK_NOEXCEPT;
116 bool lockInternal(int timeout) QT_MUTEX_LOCK_NOEXCEPT;
117 void unlockInternal() noexcept;
118
119 QBasicAtomicPointer<QMutexData> d_ptr;
120 static inline QMutexData *dummyLocked() {
121 return reinterpret_cast<QMutexData *>(quintptr(1));
122 }
123
124 friend class QMutex;
125 friend class QRecursiveMutex;
126 friend class QMutexData;
127};
128
129class Q_CORE_EXPORT QMutex : public QBasicMutex
130{
131public:
132#if defined(Q_COMPILER_CONSTEXPR) && !defined(Q_CC_INTEL)
133 constexpr QMutex() = default;
134#else
135 QMutex() { d_ptr.storeRelaxed(nullptr); }
136#endif
137 enum RecursionMode { NonRecursive, Recursive };
138 explicit QMutex(RecursionMode mode);
139 ~QMutex();
140
141 // BasicLockable concept
142 void lock() QT_MUTEX_LOCK_NOEXCEPT;
143 bool tryLock(int timeout = 0) QT_MUTEX_LOCK_NOEXCEPT;
144 // BasicLockable concept
145 void unlock() noexcept;
146
147 // Lockable concept
148 bool try_lock() QT_MUTEX_LOCK_NOEXCEPT { return tryLock(); }
149
150#if __has_include(<chrono>) || defined(Q_CLANG_QDOC)
151 // TimedLockable concept
152 template <class Rep, class Period>
153 bool try_lock_for(std::chrono::duration<Rep, Period> duration)
154 {
155 return tryLock(timeout: convertToMilliseconds(duration));
156 }
157
158 // TimedLockable concept
159 template<class Clock, class Duration>
160 bool try_lock_until(std::chrono::time_point<Clock, Duration> timePoint)
161 {
162 // Implemented in terms of try_lock_for to honor the similar
163 // requirement in N4606 § 30.4.1.3 [thread.timedmutex.requirements]/12.
164
165 return try_lock_for(timePoint - Clock::now());
166 }
167#endif
168
169 bool isRecursive() const noexcept
170 { return QBasicMutex::isRecursive(); }
171
172private:
173 Q_DISABLE_COPY(QMutex)
174 friend class QMutexLocker;
175 friend class QRecursiveMutex;
176 friend class ::tst_QMutex;
177
178#if __has_include(<chrono>)
179 template<class Rep, class Period>
180 static int convertToMilliseconds(std::chrono::duration<Rep, Period> duration)
181 {
182 // N4606 § 30.4.1.3.5 [thread.timedmutex.requirements] specifies that a
183 // duration less than or equal to duration.zero() shall result in a
184 // try_lock, unlike QMutex's tryLock with a negative duration which
185 // results in a lock.
186
187 if (duration <= duration.zero())
188 return 0;
189
190 // when converting from 'duration' to milliseconds, make sure that
191 // the result is not shorter than 'duration':
192 std::chrono::milliseconds wait = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
193 if (wait < duration)
194 wait += std::chrono::milliseconds(1);
195 Q_ASSERT(wait >= duration);
196 const auto ms = wait.count();
197 const auto maxInt = (std::numeric_limits<int>::max)();
198
199 return ms < maxInt ? int(ms) : maxInt;
200 }
201#endif
202};
203
204class QRecursiveMutex : private QMutex
205{
206 // ### Qt 6: make it independent of QMutex
207 friend class QMutexLocker;
208public:
209 Q_CORE_EXPORT QRecursiveMutex();
210 Q_CORE_EXPORT ~QRecursiveMutex();
211
212 using QMutex::lock;
213 using QMutex::tryLock;
214 using QMutex::unlock;
215 using QMutex::try_lock;
216#if __has_include(<chrono>)
217 using QMutex::try_lock_for;
218 using QMutex::try_lock_until;
219#endif
220};
221
222class Q_CORE_EXPORT QMutexLocker
223{
224public:
225#ifndef Q_CLANG_QDOC
226 inline explicit QMutexLocker(QBasicMutex *m) QT_MUTEX_LOCK_NOEXCEPT
227 {
228 Q_ASSERT_X((reinterpret_cast<quintptr>(m) & quintptr(1u)) == quintptr(0),
229 "QMutexLocker", "QMutex pointer is misaligned");
230 val = quintptr(m);
231 if (Q_LIKELY(m)) {
232 // call QMutex::lock() instead of QBasicMutex::lock()
233 static_cast<QMutex *>(m)->lock();
234 val |= 1;
235 }
236 }
237 explicit QMutexLocker(QRecursiveMutex *m) QT_MUTEX_LOCK_NOEXCEPT
238 : QMutexLocker{static_cast<QBasicMutex*>(m)} {}
239#else
240 QMutexLocker(QMutex *) { }
241 QMutexLocker(QRecursiveMutex *) {}
242#endif
243 inline ~QMutexLocker() { unlock(); }
244
245 inline void unlock() noexcept
246 {
247 if ((val & quintptr(1u)) == quintptr(1u)) {
248 val &= ~quintptr(1u);
249 mutex()->unlock();
250 }
251 }
252
253 inline void relock() QT_MUTEX_LOCK_NOEXCEPT
254 {
255 if (val) {
256 if ((val & quintptr(1u)) == quintptr(0u)) {
257 mutex()->lock();
258 val |= quintptr(1u);
259 }
260 }
261 }
262
263#if defined(Q_CC_MSVC)
264#pragma warning( push )
265#pragma warning( disable : 4312 ) // ignoring the warning from /Wp64
266#endif
267
268 inline QMutex *mutex() const
269 {
270 return reinterpret_cast<QMutex *>(val & ~quintptr(1u));
271 }
272
273#if defined(Q_CC_MSVC)
274#pragma warning( pop )
275#endif
276
277private:
278 Q_DISABLE_COPY(QMutexLocker)
279
280 quintptr val;
281};
282
283#else // !QT_CONFIG(thread) && !Q_CLANG_QDOC
284
285class Q_CORE_EXPORT QMutex
286{
287public:
288 enum RecursionMode { NonRecursive, Recursive };
289
290 inline Q_DECL_CONSTEXPR explicit QMutex(RecursionMode = NonRecursive) noexcept { }
291
292 inline void lock() noexcept {}
293 inline bool tryLock(int timeout = 0) noexcept { Q_UNUSED(timeout); return true; }
294 inline bool try_lock() noexcept { return true; }
295 inline void unlock() noexcept {}
296 inline bool isRecursive() const noexcept { return true; }
297
298#if __has_include(<chrono>)
299 template <class Rep, class Period>
300 inline bool try_lock_for(std::chrono::duration<Rep, Period> duration) noexcept
301 {
302 Q_UNUSED(duration);
303 return true;
304 }
305
306 template<class Clock, class Duration>
307 inline bool try_lock_until(std::chrono::time_point<Clock, Duration> timePoint) noexcept
308 {
309 Q_UNUSED(timePoint);
310 return true;
311 }
312#endif
313
314private:
315 Q_DISABLE_COPY(QMutex)
316};
317
318class QRecursiveMutex : public QMutex {};
319
320class Q_CORE_EXPORT QMutexLocker
321{
322public:
323 inline explicit QMutexLocker(QMutex *) noexcept {}
324 inline ~QMutexLocker() noexcept {}
325
326 inline void unlock() noexcept {}
327 void relock() noexcept {}
328 inline QMutex *mutex() const noexcept { return nullptr; }
329
330private:
331 Q_DISABLE_COPY(QMutexLocker)
332};
333
334typedef QMutex QBasicMutex;
335
336#endif // !QT_CONFIG(thread) && !Q_CLANG_QDOC
337
338QT_END_NAMESPACE
339
340#endif // QMUTEX_H
341

source code of qtbase/src/corelib/thread/qmutex.h