[libc-commits] [libc] [libc] Replace `MutexLock` with `cpp::lock_guard` (PR #89340)

Nick Desaulniers via libc-commits libc-commits at lists.llvm.org
Fri Apr 19 09:44:44 PDT 2024


================
@@ -0,0 +1,47 @@
+//===--- A simple lock_guard implementation ---------------------*- 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 LLVM_LIBC_SRC___SUPPORT_CPP_MUTEX_H
+#define LLVM_LIBC_SRC___SUPPORT_CPP_MUTEX_H
+
+namespace LIBC_NAMESPACE {
+namespace cpp {
+
+// Assume the calling thread has already obtained mutex ownership.
+struct adopt_lock_t {
+  explicit adopt_lock_t() = default;
+};
+
+// Tag used to make a scoped lock take ownership of a locked mutex.
+constexpr adopt_lock_t adopt_lock{};
+
+// An RAII class for easy locking and unlocking of mutexes.
+template <typename MutexType> class lock_guard {
+public:
+  // Calls `m.lock()` upon resource acquisition.
+  explicit lock_guard(MutexType &m) : mutex(m) { mutex.lock(); }
+
+  // Acquires ownership of the mutex object `m` without attempting to lock
+  // it. The behavior is undefined if the current thread does not hold the
+  // lock on `m`.
----------------
nickdesaulniers wrote:

```suggestion
  // Acquires ownership of the mutex object `m` without attempting to lock
  // it. The behavior is undefined if the current thread does not hold the
  // lock on `m`.  Does not call `m.lock()` upon resource acquisition.
```

https://github.com/llvm/llvm-project/pull/89340


More information about the libc-commits mailing list