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