[libc-commits] [libc] [libc] Add Darwin mutex support via os_sync primitives (PR #167722)

Shreeyash Pandey via libc-commits libc-commits at lists.llvm.org
Sun Nov 30 02:26:55 PST 2025


================
@@ -0,0 +1,66 @@
+//===--- Futex utils for Darwin -----------------------------------*- 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_THREADS_DARWIN_FUTEX_UTILS_H
+#define LLVM_LIBC_SRC___SUPPORT_THREADS_DARWIN_FUTEX_UTILS_H
+
+#include "src/__support/CPP/atomic.h"
+#include "src/__support/CPP/optional.h"
+#include "src/__support/time/abs_timeout.h"
+#include "src/__support/time/clock_conversion.h"
+
+#include <os/os_sync_wait_on_address.h>
+
+namespace LIBC_NAMESPACE_DECL {
+
+using FutexWordType = uint32_t;
+
+struct Futex : public cpp::Atomic<FutexWordType> {
+  using cpp::Atomic<FutexWordType>::Atomic;
+  using Timeout = internal::AbsTimeout;
+
+  // The Darwin futex API does not return a value on timeout, so we have to
+  // check for it manually. This means we can't use the return value to
+  // distinguish between a timeout and a successful wake-up.
+  int wait(FutexWordType val, cpp::optional<Timeout> timeout, bool) {
+    if (timeout) {
+      struct timespec now;
+      clock_gettime(timeout->is_realtime() ? CLOCK_REALTIME : CLOCK_MONOTONIC,
+                    &now);
+      const timespec &target_ts = timeout->get_timespec();
+
+      if (now.tv_sec > target_ts.tv_sec ||
+          (now.tv_sec == target_ts.tv_sec && now.tv_nsec >= target_ts.tv_nsec))
+        return ETIMEDOUT;
+    }
+
+    os_sync_wait_on_address(reinterpret_cast<void *>(this),
----------------
bojle wrote:

I've pushed changes that incorporate timeout variants of os_sync* functions. The design at the moment mimics that of linux quite closely.

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


More information about the libc-commits mailing list