1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef _LIBCPP___MUTEX_MUTEX_H
10#define _LIBCPP___MUTEX_MUTEX_H
11
12#include <__config>
13#include <__thread/support.h>
14#include <__type_traits/is_nothrow_constructible.h>
15
16#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
17# pragma GCC system_header
18#endif
19
20#if _LIBCPP_HAS_THREADS
21
22_LIBCPP_BEGIN_NAMESPACE_STD
23_LIBCPP_BEGIN_EXPLICIT_ABI_ANNOTATIONS
24
25// The glibc and Bionic implementation of pthreads implements
26// pthread_mutex_destroy as nop for regular mutexes. Additionally, Win32
27// mutexes have no destroy mechanism.
28//
29// This optimization can't be performed on Apple platforms, where
30// pthread_mutex_destroy can allow the kernel to release resources.
31// See https://llvm.org/D64298 for details.
32//
33// clang-format off
34# if (_LIBCPP_HAS_THREAD_API_PTHREAD && (defined(__GLIBC__) || defined(__BIONIC__))) || \
35 (_LIBCPP_HAS_THREAD_API_C11 && defined(__Fuchsia__)) || \
36 _LIBCPP_HAS_THREAD_API_WIN32
37// clang-format on
38# define _LIBCPP_HAS_TRIVIAL_MUTEX_DESTRUCTION 1
39# else
40# define _LIBCPP_HAS_TRIVIAL_MUTEX_DESTRUCTION 0
41# endif
42
43class _LIBCPP_EXPORTED_FROM_ABI _LIBCPP_CAPABILITY("mutex") _LIBCPP_WARN_UNUSED mutex {
44 __libcpp_mutex_t __m_ = _LIBCPP_MUTEX_INITIALIZER;
45
46public:
47 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR mutex() = default;
48
49 mutex(const mutex&) = delete;
50 mutex& operator=(const mutex&) = delete;
51
52# if _LIBCPP_HAS_TRIVIAL_MUTEX_DESTRUCTION
53 _LIBCPP_HIDE_FROM_ABI ~mutex() = default;
54# else
55 ~mutex() _NOEXCEPT;
56# endif
57
58 _LIBCPP_ACQUIRE_CAPABILITY() void lock();
59 [[__nodiscard__]] _LIBCPP_TRY_ACQUIRE_CAPABILITY(true) bool try_lock() _NOEXCEPT;
60 _LIBCPP_RELEASE_CAPABILITY() void unlock() _NOEXCEPT;
61
62 typedef __libcpp_mutex_t* native_handle_type;
63 [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI native_handle_type native_handle() { return &__m_; }
64};
65
66static_assert(is_nothrow_default_constructible<mutex>::value, "the default constructor for std::mutex must be nothrow");
67
68_LIBCPP_END_EXPLICIT_ABI_ANNOTATIONS
69_LIBCPP_END_NAMESPACE_STD
70
71#endif // _LIBCPP_HAS_THREADS
72
73#endif // _LIBCPP___MUTEX_MUTEX_H
74