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
qlocking_p.h
Go to the documentation of this file.
1// Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Marc Mutz <marc.mutz@kdab.com>
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 QLOCKING_P_H
6#define QLOCKING_P_H
7
8//
9// W A R N I N G
10// -------------
11//
12// This file is not part of the Qt API. It exists for the convenience of
13// qmutex.cpp and qmutex_unix.cpp. This header file may change from version to
14// version without notice, or even be removed.
15//
16// We mean it.
17//
18
19#include <QtCore/qmutex.h>
20#include <QtCore/private/qglobal_p.h>
21
22#include <mutex>
23
24QT_BEGIN_NAMESPACE
25
26//
27// This API is bridging the time until we can depend on C++17:
28//
29// - qt_scoped_lock returns a lock that cannot be unlocked again before the end of the scope
30// - qt_unique_lock returns a lock that can be unlock()ed and moved around
31// - for compat with QMutexLocker, qt_unique_lock supports passing by pointer.
32// Do NOT use this overload lightly; it's only for cases such as where a Q_GLOBAL_STATIC
33// may have already been deleted. In particular, do NOT port from
34// QMutexLocker locker(&mutex);
35// to
36// auto locker = qt_unique_lock(&mutex);
37// as this will not port automatically to std::unique_lock come C++17!
38//
39// The intent, come C++17, is to replace
40// qt_scoped_lock(mutex);
41// qt_unique_lock(mutex); // except qt_unique_lock(&mutex)
42// with
43// std::scoped_lock(mutex);
44// std::unique_lock(mutex);
45// resp. (C++17 meaning CTAD, guaranteed copy elision + scoped_lock available on all platforms),
46// so please use these functions only in ways which don't break this mechanical search & replace.
47//
48
49namespace {
50
51template <typename Mutex, typename Lock =
52# if defined(__cpp_lib_scoped_lock) && __cpp_lib_scoped_lock >= 201703L
53 std::scoped_lock
54# else
55 std::lock_guard
56# endif
57 <typename std::decay<Mutex>::type>
58>
59Lock qt_scoped_lock(Mutex &mutex)
60{
61 return Lock(mutex);
62}
63
64template <typename Mutex, typename Lock = std::unique_lock<typename std::decay<Mutex>::type>>
65Lock qt_unique_lock(Mutex &mutex)
66{
67 return Lock(mutex);
68}
69
70template <typename Mutex, typename Lock = std::unique_lock<typename std::decay<Mutex>::type>>
71Lock qt_unique_lock(Mutex *mutex)
72{
73 return mutex ? Lock(*mutex) : Lock() ;
74}
75
76} // unnamed namespace
77
78QT_END_NAMESPACE
79
80#endif // QLOCKING_P_H
Lock qt_scoped_lock(Mutex &mutex)
Definition qlocking_p.h:59
Lock qt_unique_lock(Mutex &mutex)
Definition qlocking_p.h:65
Lock qt_unique_lock(Mutex *mutex)
Definition qlocking_p.h:71