mirror-llvm-project/libcxx/include/__mutex/mutex.h
AnthonyCalandraGeotab 72e1037c32
[libc++][ThreadSafety] Add thread safety annotations for variadic std::scoped_lock (#204462)
The thread safety annotations on std::scoped_lock were previously only
applied to the empty and single-mutex specializations. The general
variadic specialization carried no annotations, so -Wthread-safety
considered none of the mutexes held inside a multi-mutex scoped_lock
block and reported the guarded data accessed there as unprotected.

Now that Clang supports pack expansion inside thread safety attributes
(landed for Clang 21), annotate the variadic scoped_lock with
acquire_capability/requires_capability on its constructors,
release_capability on its destructor, and scoped_lockable on the class.

Fixes #42000.

Co-authored-by: Anthony Calandra <anthony@anthony-calandra.com>
2026-07-07 17:52:56 +02:00

55 lines
1.7 KiB
C++

//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP___MUTEX_MUTEX_H
#define _LIBCPP___MUTEX_MUTEX_H
#include <__config>
#include <__thread/support.h>
#include <__type_traits/is_nothrow_constructible.h>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
# pragma GCC system_header
#endif
#if _LIBCPP_HAS_THREADS
_LIBCPP_BEGIN_NAMESPACE_STD
_LIBCPP_BEGIN_EXPLICIT_ABI_ANNOTATIONS
class _LIBCPP_EXPORTED_FROM_ABI _LIBCPP_CAPABILITY("mutex") mutex {
__libcpp_mutex_t __m_ = _LIBCPP_MUTEX_INITIALIZER;
public:
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR mutex() = default;
mutex(const mutex&) = delete;
mutex& operator=(const mutex&) = delete;
# if _LIBCPP_HAS_TRIVIAL_MUTEX_DESTRUCTION
_LIBCPP_HIDE_FROM_ABI ~mutex() = default;
# else
~mutex() _NOEXCEPT;
# endif
_LIBCPP_ACQUIRE_CAPABILITY() void lock();
[[__nodiscard__]] _LIBCPP_TRY_ACQUIRE_CAPABILITY(true) bool try_lock() _NOEXCEPT;
_LIBCPP_RELEASE_CAPABILITY() void unlock() _NOEXCEPT;
typedef __libcpp_mutex_t* native_handle_type;
[[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI native_handle_type native_handle() { return &__m_; }
};
static_assert(is_nothrow_default_constructible<mutex>::value, "the default constructor for std::mutex must be nothrow");
_LIBCPP_END_EXPLICIT_ABI_ANNOTATIONS
_LIBCPP_END_NAMESPACE_STD
#endif // _LIBCPP_HAS_THREADS
#endif // _LIBCPP___MUTEX_MUTEX_H