[libc-commits] [libc] [libc] implement PI mutex (PR #199393)
Schrodinger ZHU Yifan via libc-commits
libc-commits at lists.llvm.org
Sun May 24 09:59:44 PDT 2026
================
@@ -0,0 +1,185 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Linux priority inheritance mutex support.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_THREADS_LINUX_PI_MUTEX_H
+#define LLVM_LIBC_SRC___SUPPORT_THREADS_LINUX_PI_MUTEX_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/optional.h"
+#include "src/__support/OSUtil/syscall.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
+#include "src/__support/threads/identifier.h"
+#include "src/__support/threads/linux/futex_utils.h"
+#include "src/__support/threads/linux/futex_word.h"
+#include "src/__support/threads/mutex_common.h"
+
+#include <linux/futex.h>
+
+#ifdef LIBC_COPT_TIMEOUT_ENSURE_MONOTONICITY
+#include "src/__support/time/monotonicity.h"
+#endif
+
+namespace LIBC_NAMESPACE_DECL {
+
+class PIMutexRef {
+public:
+ enum class Type { Normal, ErrorChecking, Recursive };
+
+protected:
+ Futex &owner;
+ Type type;
+ // Number of recursive locks minus one. This pointer must be provided
+ // if type == Recursive
+ size_t *recursive_count;
+
+public:
+ LIBC_INLINE constexpr PIMutexRef(Futex &owner, Type type,
+ size_t *recursive_count = nullptr)
+ : owner(owner), type(type), recursive_count(recursive_count) {}
+ LIBC_INLINE MutexError try_lock() {
+ FutexWordType old_owner = 0;
+ auto current = static_cast<FutexWordType>(internal::gettid());
+ if (owner.compare_exchange_strong(old_owner, current,
+ cpp::MemoryOrder::ACQUIRE,
+ cpp::MemoryOrder::RELAXED))
+ return MutexError::NONE;
+
+ if (current == (old_owner & FUTEX_TID_MASK)) {
+ switch (type) {
+ case Type::Normal:
+ break;
+ case Type::ErrorChecking:
+ return MutexError::DEADLOCK;
+ case Type::Recursive:
+ if (LIBC_UNLIKELY(*recursive_count ==
+ cpp::numeric_limits<size_t>::max()))
+ return MutexError::OVERFLOW;
+ *recursive_count += 1;
+ return MutexError::NONE;
----------------
SchrodingerZhu wrote:
This is explicitly said
https://github.com/llvm/llvm-project/pull/199393
More information about the libc-commits
mailing list