libstdc++
std_mutex.h
Go to the documentation of this file.
1 // std::mutex implementation -*- C++ -*-
2 
3 // Copyright (C) 2003-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/std_mutex.h
26  * This is an internal header file, included by other library headers.
27  * Do not attempt to use it directly. @headername{mutex}
28  */
29 
30 #ifndef _GLIBCXX_MUTEX_H
31 #define _GLIBCXX_MUTEX_H 1
32 
33 #ifdef _GLIBCXX_SYSHDR
34 #pragma GCC system_header
35 #endif
36 
37 #if __cplusplus < 201103L
38 # include <bits/c++0x_warning.h>
39 #else
40 
41 #include <errno.h> // EBUSY
42 #include <bits/chrono.h>
43 #include <bits/functexcept.h>
44 #include <bits/gthr.h>
45 
46 namespace std _GLIBCXX_VISIBILITY(default)
47 {
48 _GLIBCXX_BEGIN_NAMESPACE_VERSION
49 
50  /**
51  * @defgroup mutexes Mutexes
52  * @ingroup concurrency
53  *
54  * Classes for mutex support.
55  * @{
56  */
57 
58 #ifdef _GLIBCXX_HAS_GTHREADS
59  /// @cond undocumented
60 
61  // Common base class for std::mutex and std::timed_mutex
62  class __mutex_base
63  {
64  protected:
65  typedef __gthread_mutex_t __native_type;
66 
67 #ifdef __GTHREAD_MUTEX_INIT
68  __native_type _M_mutex = __GTHREAD_MUTEX_INIT;
69 
70  constexpr __mutex_base() noexcept = default;
71 #else
72  __native_type _M_mutex;
73 
74  __mutex_base() noexcept
75  {
76  // XXX EAGAIN, ENOMEM, EPERM, EBUSY(may), EINVAL(may)
77  __GTHREAD_MUTEX_INIT_FUNCTION(&_M_mutex);
78  }
79 
80  ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); }
81 #endif
82 
83  __mutex_base(const __mutex_base&) = delete;
84  __mutex_base& operator=(const __mutex_base&) = delete;
85  };
86  /// @endcond
87 
88  /** The standard mutex type.
89  *
90  * A simple, non-recursive, non-timed mutex.
91  *
92  * Do not call `lock()` and `unlock()` directly, use a scoped lock type
93  * such as `std::unique_lock`, `std::lock_guard`, or (since C++17)
94  * `std::scoped_lock`.
95  *
96  * @headerfile mutex
97  * @since C++11
98  */
99  class mutex : private __mutex_base
100  {
101  public:
102  typedef __native_type* native_handle_type;
103 
104 #ifdef __GTHREAD_MUTEX_INIT
105  constexpr
106 #endif
107  mutex() noexcept = default;
108  ~mutex() = default;
109 
110  mutex(const mutex&) = delete;
111  mutex& operator=(const mutex&) = delete;
112 
113  void
114  lock()
115  {
116  int __e = __gthread_mutex_lock(&_M_mutex);
117 
118  // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
119  if (__e)
120  __throw_system_error(__e);
121  }
122 
123  _GLIBCXX_NODISCARD
124  bool
125  try_lock() noexcept
126  {
127  // XXX EINVAL, EAGAIN, EBUSY
128  return !__gthread_mutex_trylock(&_M_mutex);
129  }
130 
131  void
132  unlock()
133  {
134  // XXX EINVAL, EAGAIN, EPERM
135  __gthread_mutex_unlock(&_M_mutex);
136  }
137 
138  native_handle_type
139  native_handle() noexcept
140  { return &_M_mutex; }
141  };
142 
143  /// @cond undocumented
144 
145  // Implementation details for std::condition_variable
146  class __condvar
147  {
148  using timespec = __gthread_time_t;
149 
150  public:
151  __condvar() noexcept
152  {
153 #ifndef __GTHREAD_COND_INIT
154  __GTHREAD_COND_INIT_FUNCTION(&_M_cond);
155 #endif
156  }
157 
158  ~__condvar()
159  {
160  int __e __attribute__((__unused__)) = __gthread_cond_destroy(&_M_cond);
161  __glibcxx_assert(__e != EBUSY); // threads are still blocked
162  }
163 
164  __condvar(const __condvar&) = delete;
165  __condvar& operator=(const __condvar&) = delete;
166 
167  __gthread_cond_t* native_handle() noexcept { return &_M_cond; }
168 
169  // Expects: Calling thread has locked __m.
170  void
171  wait(mutex& __m)
172  {
173  int __e __attribute__((__unused__))
174  = __gthread_cond_wait(&_M_cond, __m.native_handle());
175  __glibcxx_assert(__e == 0);
176  }
177 
178  void
179  wait_until(mutex& __m, timespec& __abs_time)
180  {
181  __gthread_cond_timedwait(&_M_cond, __m.native_handle(), &__abs_time);
182  }
183 
184 #ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
185  void
186  wait_until(mutex& __m, clockid_t __clock, timespec& __abs_time)
187  {
188  pthread_cond_clockwait(&_M_cond, __m.native_handle(), __clock,
189  &__abs_time);
190  }
191 #endif
192 
193  void
194  notify_one() noexcept
195  {
196  int __e __attribute__((__unused__)) = __gthread_cond_signal(&_M_cond);
197  __glibcxx_assert(__e == 0);
198  }
199 
200  void
201  notify_all() noexcept
202  {
203  int __e __attribute__((__unused__)) = __gthread_cond_broadcast(&_M_cond);
204  __glibcxx_assert(__e == 0);
205  }
206 
207  protected:
208 #ifdef __GTHREAD_COND_INIT
209  __gthread_cond_t _M_cond = __GTHREAD_COND_INIT;
210 #else
211  __gthread_cond_t _M_cond;
212 #endif
213  };
214 
215 namespace chrono
216 {
217 #pragma GCC diagnostic push
218 #pragma GCC diagnostic ignored "-Wc++17-extensions"
219  // Convert a time_point to an absolute time represented as __gthread_time_t
220  // (which is typically just a typedef for struct timespec).
221  template<typename _Clock, typename _Dur>
222  [[__nodiscard__]] _GLIBCXX14_CONSTEXPR inline
223  __gthread_time_t
224  __to_timeout_gthread_time_t(const time_point<_Clock, _Dur>& __t)
225  {
226  auto __ts = chrono::__to_timeout_timespec(__t.time_since_epoch());
227  if constexpr (is_same<::timespec, __gthread_time_t>::value)
228  return __ts;
229  else if constexpr (is_convertible<::timespec, __gthread_time_t>::value)
230  return __ts;
231  else if constexpr (is_scalar<__gthread_time_t>::value) // Assume seconds:
232  return static_cast<__gthread_time_t>(__ts.tv_sec);
233  else // Assume this works and the members are in the correct order:
234  return __gthread_time_t{ __ts.tv_sec, __ts.tv_nsec };
235  }
236 #pragma GCC diagnostic pop
237 }
238  /// @endcond
239 #endif // _GLIBCXX_HAS_GTHREADS
240 
241  /// Do not acquire ownership of the mutex.
242  struct defer_lock_t { explicit defer_lock_t() = default; };
243 
244  /// Try to acquire ownership of the mutex without blocking.
245  struct try_to_lock_t { explicit try_to_lock_t() = default; };
246 
247  /// Assume the calling thread has already obtained mutex ownership
248  /// and manage it.
249  struct adopt_lock_t { explicit adopt_lock_t() = default; };
250 
251  /// Tag used to prevent a scoped lock from acquiring ownership of a mutex.
252  _GLIBCXX17_INLINE constexpr defer_lock_t defer_lock { };
253 
254  /// Tag used to prevent a scoped lock from blocking if a mutex is locked.
255  _GLIBCXX17_INLINE constexpr try_to_lock_t try_to_lock { };
256 
257  /// Tag used to make a scoped lock take ownership of a locked mutex.
258  _GLIBCXX17_INLINE constexpr adopt_lock_t adopt_lock { };
259 
260  /** @brief A simple scoped lock type.
261  *
262  * A lock_guard controls mutex ownership within a scope, releasing
263  * ownership in the destructor.
264  *
265  * @headerfile mutex
266  * @since C++11
267  */
268  template<typename _Mutex>
270  {
271  public:
272  typedef _Mutex mutex_type;
273 
274  [[__nodiscard__]]
275  explicit lock_guard(mutex_type& __m) : _M_device(__m)
276  { _M_device.lock(); }
277 
278  [[__nodiscard__]]
279  lock_guard(mutex_type& __m, adopt_lock_t) noexcept : _M_device(__m)
280  { } // calling thread owns mutex
281 
282  ~lock_guard()
283  { _M_device.unlock(); }
284 
285  lock_guard(const lock_guard&) = delete;
286  lock_guard& operator=(const lock_guard&) = delete;
287 
288  private:
289  mutex_type& _M_device;
290  };
291 
292  /// @} group mutexes
293 _GLIBCXX_END_NAMESPACE_VERSION
294 } // namespace
295 #endif // C++11
296 #endif // _GLIBCXX_MUTEX_H
constexpr try_to_lock_t try_to_lock
Tag used to prevent a scoped lock from blocking if a mutex is locked.
Definition: std_mutex.h:255
constexpr adopt_lock_t adopt_lock
Tag used to make a scoped lock take ownership of a locked mutex.
Definition: std_mutex.h:258
constexpr defer_lock_t defer_lock
Tag used to prevent a scoped lock from acquiring ownership of a mutex.
Definition: std_mutex.h:252
ISO C++ entities toplevel namespace is std.
Do not acquire ownership of the mutex.
Definition: std_mutex.h:242
Try to acquire ownership of the mutex without blocking.
Definition: std_mutex.h:245
Assume the calling thread has already obtained mutex ownership and manage it.
Definition: std_mutex.h:249
A simple scoped lock type.
Definition: std_mutex.h:270