xref: /aosp_15_r20/external/llvm-libc/src/__support/CPP/mutex.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===--- A self contained equivalent of std::mutex --------------*- C++ -*-===//
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 LLVM_LIBC_SRC___SUPPORT_CPP_MUTEX_H
10 #define LLVM_LIBC_SRC___SUPPORT_CPP_MUTEX_H
11 
12 #include "src/__support/macros/config.h"
13 
14 namespace LIBC_NAMESPACE_DECL {
15 namespace cpp {
16 
17 // Assume the calling thread has already obtained mutex ownership.
18 struct adopt_lock_t {
19   explicit adopt_lock_t() = default;
20 };
21 
22 // Tag used to make a scoped lock take ownership of a locked mutex.
23 constexpr adopt_lock_t adopt_lock{};
24 
25 // An RAII class for easy locking and unlocking of mutexes.
26 template <typename MutexType> class lock_guard {
27   MutexType &mutex;
28 
29 public:
30   // Calls `m.lock()` upon resource acquisition.
lock_guard(MutexType & m)31   explicit lock_guard(MutexType &m) : mutex(m) { mutex.lock(); }
32 
33   // Acquires ownership of the mutex object `m` without attempting to lock
34   // it. The behavior is undefined if the current thread does not hold the
35   // lock on `m`. Does not call `m.lock()` upon resource acquisition.
lock_guard(MutexType & m,adopt_lock_t)36   lock_guard(MutexType &m, adopt_lock_t /* t */) : mutex(m) {}
37 
~lock_guard()38   ~lock_guard() { mutex.unlock(); }
39 
40   // non-copyable
41   lock_guard &operator=(const lock_guard &) = delete;
42   lock_guard(const lock_guard &) = delete;
43 };
44 
45 // Deduction guide for lock_guard to suppress CTAD warnings.
46 template <typename T> lock_guard(T &) -> lock_guard<T>;
47 
48 } // namespace cpp
49 } // namespace LIBC_NAMESPACE_DECL
50 
51 #endif // LLVM_LIBC_SRC___SUPPORT_CPP_MUTEX_H
52