[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:45 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`.
+  lock_guard(MutexType &m, adopt_lock_t t) : mutex(m) {}
+
+  ~lock_guard() { mutex.unlock(); }
+
+private:
+  // non-copyable
+  lock_guard &operator=(const lock_guard &) = delete;
+  lock_guard(const lock_guard &) = delete;
+
+  MutexType &mutex;
----------------
nickdesaulniers wrote:

If you put the private members first before the public ones, you can omit the private keyword.  I also find it nicer to have the data members listed first in a class defintion.

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


More information about the libc-commits mailing list