From 390c4b9842d209cea26e920bada13684fbaf14ab Mon Sep 17 00:00:00 2001 From: Huang Qi Date: Wed, 12 Mar 2025 20:16:00 +0800 Subject: [PATCH] sys/pal/unix/sync/mutex: Fix Mutex::new() on NuttX PTHREAD_MUTEX_INITIALIZER is highly configurable on NuttX, making it difficult to use a hardcoded initializer from libc crate in Rust way. Instead, call pthread_mutex_init() to initialize the mutex with default attributes, ensuring consistent behavior with PTHREAD_MUTEX_INITIALIZER. * Added conditional compilation for NuttX target * Replaced PTHREAD_MUTEX_INITIALIZER with pthread_mutex_init() for NuttX * Ensured consistent mutex initialization behavior across platforms --- library/std/src/sys/pal/unix/sync/mutex.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/library/std/src/sys/pal/unix/sync/mutex.rs b/library/std/src/sys/pal/unix/sync/mutex.rs index 557e70af94ba7..6d6b262da6288 100644 --- a/library/std/src/sys/pal/unix/sync/mutex.rs +++ b/library/std/src/sys/pal/unix/sync/mutex.rs @@ -9,10 +9,26 @@ pub struct Mutex { } impl Mutex { + #[cfg(not(target_os = "nuttx"))] pub fn new() -> Mutex { Mutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) } } + #[cfg(target_os = "nuttx")] + pub fn new() -> Mutex { + // PTHREAD_MUTEX_INITIALIZER is highly configurable on NuttX, so it's + // hard to use a hardcoded initializer from libc. + // Instead, call pthread_mutex_init() to initialize the mutex with the + // default attributes to get the same behavior as PTHREAD_MUTEX_INITIALIZER. + let mut mutex = Mutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) }; + + unsafe { + libc::pthread_mutex_init(mutex.raw(), core::ptr::null()); + } + + mutex + } + pub(super) fn raw(&self) -> *mut libc::pthread_mutex_t { self.inner.get() }