libstdc++
atomic_wait.h
Go to the documentation of this file.
1// -*- C++ -*- header.
2
3// Copyright (C) 2020-2026 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/atomic_wait.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{atomic}
28 */
29
30#ifndef _GLIBCXX_ATOMIC_WAIT_H
31#define _GLIBCXX_ATOMIC_WAIT_H 1
32
33#ifdef _GLIBCXX_SYSHDR
34#pragma GCC system_header
35#endif
36
37#include <bits/version.h>
38
39#if __glibcxx_atomic_wait
40#include <bits/gthr.h>
41#include <ext/numeric_traits.h>
42
43#include <bits/stl_pair.h>
44
45namespace std _GLIBCXX_VISIBILITY(default)
46{
47_GLIBCXX_BEGIN_NAMESPACE_VERSION
48
49 namespace __detail
50 {
51 // TODO: this needs to be false for types with padding, e.g. __int20.
52 // TODO: should this be true only for integral, enum, and pointer types?
53 template<typename _Tp>
54 concept __waitable
55 = is_scalar_v<_Tp> && __builtin_popcountg(sizeof(_Tp)) == 1
56 && (sizeof(_Tp) <= sizeof(__UINT64_TYPE__));
57 }
58
59#if defined _GLIBCXX_HAVE_LINUX_FUTEX
60 namespace __detail
61 {
62 // Use futex syscall on int objects.
63 using __platform_wait_t = int;
64 inline constexpr size_t __platform_wait_alignment = 4;
65 }
66 // Defined to true for a subset of __waitable types which are statically
67 // known to definitely be able to use futex, not a proxy wait.
68 template<typename _Tp>
69 inline constexpr bool __platform_wait_uses_type
70 = __detail::__waitable<_Tp>
71 && sizeof(_Tp) == sizeof(int) && alignof(_Tp) >= 4;
72#else
73// define _GLIBCX_HAVE_PLATFORM_WAIT and implement __platform_wait()
74// and __platform_notify() if there is a more efficient primitive supported
75// by the platform (e.g. __ulock_wait()/__ulock_wake()) which is better than
76// a mutex/condvar based wait.
77 namespace __detail
78 {
79# if ATOMIC_LONG_LOCK_FREE == 2
80 using __platform_wait_t = unsigned long;
81# else
82 using __platform_wait_t = unsigned int;
83# endif
84 inline constexpr size_t __platform_wait_alignment
85 = sizeof(__platform_wait_t) < __alignof__(__platform_wait_t)
86 ? __alignof__(__platform_wait_t) : sizeof(__platform_wait_t);
87 } // namespace __detail
88
89 // This must be false for the general case where we don't know of any
90 // futex-like syscall.
91 template<typename>
92 inline constexpr bool __platform_wait_uses_type = false;
93#endif
94
95 namespace __detail
96 {
97 inline void
98 __thread_yield() noexcept
99 {
100#if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
101 __gthread_yield();
102#endif
103 }
104
105 inline void
106 __thread_relax() noexcept
107 {
108#if defined __i386__ || defined __x86_64__
109 __builtin_ia32_pause();
110#else
111 __thread_yield();
112#endif
113 }
114
115 // return true if equal
116 template<typename _Tp>
117 inline bool
118 __atomic_eq(const _Tp& __a, const _Tp& __b)
119 {
120 // TODO make this do the correct padding bit ignoring comparison
121 return __builtin_memcmp(std::addressof(__a), std::addressof(__b),
122 sizeof(_Tp)) == 0;
123 }
124
125 // Storage for up to 64 bits of value, should be considered opaque bits.
126 using __wait_value_type = __UINT64_TYPE__;
127
128 // lightweight std::optional<__wait_value_type>
129 struct __wait_result_type
130 {
131 __wait_value_type _M_val;
132 unsigned char _M_has_val : 1; // _M_val value was loaded before return.
133 unsigned char _M_timeout : 1; // Waiting function ended with timeout.
134 unsigned char _M_unused : 6; // padding
135 };
136
137 enum class __wait_flags : __UINT_LEAST32_TYPE__
138 {
139 __abi_version = 0x00000000,
140 // currently unused = 1,
141 __track_contention = 2,
142 __do_spin = 4,
143 __spin_only = 8, // Ignored unless __do_spin is also set.
144 // __abi_version_mask = 0xff000000,
145 };
146
147 [[__gnu__::__always_inline__]]
148 constexpr __wait_flags
149 operator|(__wait_flags __l, __wait_flags __r) noexcept
150 {
152 return static_cast<__wait_flags>(static_cast<_Ut>(__l)
153 | static_cast<_Ut>(__r));
154 }
155
156 [[__gnu__::__always_inline__]]
157 constexpr __wait_flags&
158 operator|=(__wait_flags& __l, __wait_flags __r) noexcept
159 { return __l = __l | __r; }
160
161 // Simple aggregate containing arguments used by implementation details.
162 struct __wait_args_base
163 {
164 __wait_flags _M_flags;
165 int _M_order = __ATOMIC_ACQUIRE;
166 __wait_value_type _M_old = 0;
167 void* _M_wait_state = nullptr;
168 const void* _M_obj = nullptr; // The address of the object to wait on.
169 unsigned char _M_obj_size = 0; // The size of that object.
170
171 // Test whether _M_flags & __flags is non-zero.
172 bool
173 operator&(__wait_flags __flags) const noexcept
174 {
175 using _Ut = underlying_type_t<__wait_flags>;
176 return static_cast<_Ut>(_M_flags) & static_cast<_Ut>(__flags);
177 }
178 };
179
180 // Utility for populating a __wait_args_base structure.
181 struct __wait_args : __wait_args_base
182 {
183 template<typename _Tp> requires (!is_same_v<_Tp, __wait_args>)
184 explicit
185 __wait_args(const _Tp* __addr, bool __bare_wait = false) noexcept
186 : __wait_args_base{ _S_flags_for(__addr, __bare_wait) }
187 {
188 _M_obj = __addr; // Might be replaced by _M_setup_wait
189 if constexpr (__waitable<_Tp>)
190 // __wait_impl might be able to wait directly on __addr
191 // instead of using a proxy, depending on its size.
192 _M_obj_size = sizeof(_Tp);
193 }
194
195 __wait_args(const __platform_wait_t* __addr, __platform_wait_t __old,
196 int __order, bool __bare_wait = false) noexcept
197 : __wait_args(__addr, __bare_wait)
198 {
199 _M_order = __order;
200 _M_old = __old;
201 }
202
203 __wait_args(const __wait_args&) noexcept = default;
204 __wait_args& operator=(const __wait_args&) noexcept = default;
205
206 template<typename _Tp, typename _ValFn>
207 _Tp
208 _M_setup_wait(const _Tp* __addr, _ValFn __vfn)
209 {
210 static_assert(is_same_v<_Tp, decay_t<decltype(__vfn())>>);
211
212 if constexpr (!__platform_wait_uses_type<_Tp>)
213 if (_M_setup_proxy_wait(__addr))
214 {
215 // We will use a proxy wait for this object.
216 // The library has set _M_wait_state, _M_obj, _M_obj_size,
217 // and _M_old.
218 // Call __vfn to load the current value from *__addr
219 // (which must happen after the call to _M_setup_proxy_wait).
220 return __vfn();
221 }
222
223 // We will use a futex-like operation to wait on this object,
224 // so just load the value, store it into _M_old, and return it.
225 return _M_store(__vfn());
226 }
227
228 // Called after a wait returns, to prepare to wait again.
229 template<typename _Tp, typename _ValFn>
230 _Tp
231 _M_on_wake(const _Tp* __addr, _ValFn __vfn, __wait_result_type __res)
232 {
233 if constexpr (!__platform_wait_uses_type<_Tp>) // maybe a proxy wait
234 if (_M_obj != __addr) // definitely a proxy wait
235 {
236 if (__res._M_has_val)
237 // Previous wait loaded a recent value from the proxy.
238 _M_old = __res._M_val;
239 else // Load a new value from the proxy and store in _M_old.
240 (void) _M_setup_proxy_wait(nullptr);
241 // Read the current value of *__addr
242 return __vfn();
243 }
244
245 if (__res._M_has_val) // The previous wait loaded a recent value.
246 {
247 _M_old = __res._M_val;
248
249 // Not a proxy wait, so the value in __res._M_val was loaded
250 // from *__addr and we don't need to call __vfn().
251 if constexpr (sizeof(_Tp) == sizeof(__UINT64_TYPE__))
252 return __builtin_bit_cast(_Tp, (__UINT64_TYPE__)_M_old);
253 else if constexpr (sizeof(_Tp) == sizeof(__UINT32_TYPE__))
254 return __builtin_bit_cast(_Tp, (__UINT32_TYPE__)_M_old);
255 else if constexpr (sizeof(_Tp) == sizeof(__UINT16_TYPE__))
256 return __builtin_bit_cast(_Tp, (__UINT16_TYPE__)_M_old);
257 else if constexpr (sizeof(_Tp) == sizeof(__UINT8_TYPE__))
258 return __builtin_bit_cast(_Tp, (__UINT8_TYPE__)_M_old);
259 else // Should be a proxy wait for this size!
260 __glibcxx_assert(false);
261 }
262 else
263 return _M_store(__vfn());
264 }
265
266 private:
267 // Store __val in _M_old.
268 // pre: This must be a non-proxy wait.
269 template<typename _Tp>
270 [[__gnu__::__always_inline__]]
271 _Tp
272 _M_store(_Tp __val)
273 {
274 // We have to consider various sizes, because a future libstdc++.so
275 // might enable non-proxy waits for additional sizes.
276 if constexpr (sizeof(_Tp) == sizeof(__UINT64_TYPE__))
277 _M_old = __builtin_bit_cast(__UINT64_TYPE__, __val);
278 else if constexpr (sizeof(_Tp) == sizeof(__UINT32_TYPE__))
279 _M_old = __builtin_bit_cast(__UINT32_TYPE__, __val);
280 else if constexpr (sizeof(_Tp) == sizeof(__UINT16_TYPE__))
281 _M_old = __builtin_bit_cast(__UINT16_TYPE__, __val);
282 else if constexpr (sizeof(_Tp) == sizeof(__UINT8_TYPE__))
283 _M_old = __builtin_bit_cast(__UINT8_TYPE__, __val);
284 else // Should be a proxy wait for this size!
285 __glibcxx_assert(false);
286 return __val;
287 }
288
289 // Returns true if a proxy wait will be used for __addr, false otherwise.
290 // If true, _M_wait_state, _M_obj, _M_obj_size, and _M_old are set.
291 // If false, data members are unchanged.
292 bool
293 _M_setup_proxy_wait(const void* __addr);
294
295 template<typename _Tp>
296 static constexpr __wait_flags
297 _S_flags_for(const _Tp*, bool __bare_wait) noexcept
298 {
299 using enum __wait_flags;
300 __wait_flags __res = __abi_version | __do_spin;
301 if (!__bare_wait)
302 __res |= __track_contention;
303 return __res;
304 }
305 };
306
307 __wait_result_type
308 __wait_impl(const void* __addr, __wait_args_base&);
309
310 void
311 __notify_impl(const void* __addr, bool __all, const __wait_args_base&);
312 } // namespace __detail
313
314 // Wait on __addr while __pred(__vfn()) is false.
315 // If __bare_wait is false, increment a counter while waiting.
316 // For callers that keep their own count of waiters, use __bare_wait=true.
317 // The effect of __vfn() must be an atomic load from __addr and nothing else.
318 template<typename _Tp, typename _Pred, typename _ValFn>
319 void
320 __atomic_wait_address(const _Tp* __addr, _Pred&& __pred, _ValFn&& __vfn,
321 bool __bare_wait = false) noexcept
322 {
323 __detail::__wait_args __args{ __addr, __bare_wait };
324 _Tp __val = __args._M_setup_wait(__addr, __vfn);
325 while (!__pred(__val))
326 {
327 auto __res = __detail::__wait_impl(__addr, __args);
328 __val = __args._M_on_wake(__addr, __vfn, __res);
329 }
330 // C++26 will return __val
331 }
332
333 // Wait on __addr while *__addr == __old is true.
334 inline void
335 __atomic_wait_address_v(const __detail::__platform_wait_t* __addr,
336 __detail::__platform_wait_t __old,
337 int __order, bool __bare_wait = false)
338 {
339 // This function must not be used if __wait_impl might use a proxy wait:
340 __glibcxx_assert(__platform_wait_uses_type<__detail::__platform_wait_t>);
341
342 __detail::__wait_args __args{ __addr, __old, __order, __bare_wait };
343 // C++26 will not ignore the return value here
344 __detail::__wait_impl(__addr, __args);
345 }
346
347 // Wait on __addr while __vfn() == __old is true.
348 template<typename _Tp, typename _ValFn>
349 void
350 __atomic_wait_address_v(const _Tp* __addr, _Tp __old,
351 _ValFn __vfn) noexcept
352 {
353 auto __pfn = [&](const _Tp& __val)
354 { return !__detail::__atomic_eq(__old, __val); };
355 std::__atomic_wait_address(__addr, __pfn, forward<_ValFn>(__vfn));
356 }
357
358 template<typename _Tp>
359 void
360 __atomic_notify_address(const _Tp* __addr, bool __all,
361 bool __bare_wait = false) noexcept
362 {
363 __detail::__wait_args __args{ __addr, __bare_wait };
364 __detail::__notify_impl(__addr, __all, __args);
365 }
366
367_GLIBCXX_END_NAMESPACE_VERSION
368} // namespace std
369#endif // __glibcxx_atomic_wait
370#endif // _GLIBCXX_ATOMIC_WAIT_H
typename underlying_type< _Tp >::type underlying_type_t
Alias template for underlying_type.
Definition type_traits:2919
typename decay< _Tp >::type decay_t
Alias template for decay.
Definition type_traits:2903
constexpr _Tp * addressof(_Tp &__r) noexcept
Returns the actual address of the object or function referenced by r, even in the presence of an over...
Definition move.h:176
constexpr _Tp && forward(typename std::remove_reference< _Tp >::type &__t) noexcept
Forward an lvalue.
Definition move.h:72
ISO C++ entities toplevel namespace is std.
constexpr bitset< _Nb > operator|(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1614
constexpr bitset< _Nb > operator&(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition bitset:1604
Implementation details not part of the namespace std interface.