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

Nick Desaulniers via libc-commits libc-commits at lists.llvm.org
Mon Apr 22 13:20:21 PDT 2024


================
@@ -0,0 +1,47 @@
+//===--- A self contained equivalent of std::mutex --------------*- 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 {
+  MutexType &mutex;
+
+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`. Does not call `m.lock` upon resource acquisition.
+  lock_guard(MutexType &m, adopt_lock_t t) : mutex(m) {}
+
+  ~lock_guard() { mutex.unlock(); }
+
+private:
----------------
nickdesaulniers wrote:

If you're just deleting these, I don't think you need to switch back to `private` here.  Are you able to remove this?

```suggestion
```

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


More information about the libc-commits mailing list