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
qlatch_p.h
Go to the documentation of this file.
1// Copyright (C) 2024 Intel Corporation.
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 QLATCH_P_H
6#define QLATCH_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 purely as an implementation
13// detail. This header file may change from version to version without notice,
14// or even be removed.
15//
16// We mean it.
17//
18
19#include <QtCore/qbasicatomic.h>
20#include <QtCore/qtsan_impl.h>
21
22#include <private/qglobal_p.h>
23
24#include <limits>
25
26QT_BEGIN_NAMESPACE
27
28class QLatch
29{
30public:
31 constexpr explicit QLatch(int expected) noexcept
32 : counter(expected | NoWaiters)
33 {}
34
35 int pending() const noexcept
36 {
37 return (counter.loadAcquire() & CounterMask);
38 }
39
40 void countDown(int n = 1) noexcept
41 {
42 QtTsan::latchCountDown(&counter);
43 if (counter.fetchAndSubRelease(n) == n) // addAndFetch(n) == 0
44 wakeUp();
45 }
46
47 bool tryWait() const noexcept
48 {
49 if (pending() != 0)
50 return false;
51 QtTsan::latchWait(&counter);
52 return true;
53 }
54
55 void wait() noexcept // not const
56 {
57 if (int current = counter.loadAcquire(); (current & CounterMask) != 0) {
58 waitInternal(current);
59 QtTsan::latchWait(&counter);
60 }
61 }
62
63 void arriveAndWait(int n = 1) noexcept
64 {
65 countDown(n);
66 wait();
67 }
68
69 // API compatible with C++20:
70 static constexpr int max() noexcept { return std::numeric_limits<int>::max(); }
71 void count_down(int n = 1) noexcept { countDown(n); }
72 bool try_wait() const noexcept { return tryWait(); }
73 void arrive_and_wait(int n = 1) noexcept { arriveAndWait(n); }
74
75private:
76 static constexpr int NoWaitersBit = 31;
77 static constexpr int NoWaiters = 1 << NoWaitersBit;
78 static constexpr int CounterMask = ~NoWaiters;
79 QBasicAtomicInt counter;
80
81 Q_DISABLE_COPY_MOVE(QLatch)
82
83#ifdef QATOMICWAIT_USE_FALLBACK
84# define Q_LATCH_EXPORT /* being linked into the unit test */
85#else
86# define Q_LATCH_EXPORT Q_CORE_EXPORT
87#endif
88
89 void Q_LATCH_EXPORT waitInternal(int current) noexcept;
90 void Q_LATCH_EXPORT wakeUp() noexcept;
91
92#undef Q_LATCH_EXPORT
93};
94
95QT_END_NAMESPACE
96
97#endif // QLATCH_P_H
#define __has_builtin(x)
static constexpr bool ForcedFallbackAtomicWait
Definition qlatch.cpp:18
#define Q_LATCH_EXPORT
Definition qlatch_p.h:86