Skip to content

Commit

Permalink
std: use os_unfair_lock for Mutex on Apple platforms
Browse files Browse the repository at this point in the history
  • Loading branch information
joboet committed Mar 9, 2024
1 parent 113f7e9 commit 76b3461
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@
#![feature(str_internals)]
#![feature(strict_provenance)]
#![feature(strict_provenance_atomic_ptr)]
#![feature(sync_unsafe_cell)]
// tidy-alphabetical-end
//
// Library features (alloc):
Expand Down
47 changes: 47 additions & 0 deletions library/std/src/sys/locks/mutex/apple.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//! Mutex for Apple platforms.
//!
//! On Apple platforms, priority inheritance is the default for locks. To avoid
//! having to use pthread's mutex, which needs some tricks to work correctly, we
//! instead use `os_unfair_lock`, which is small, movable and supports priority-
//! inheritance and appeared with macOS 10.12, which is exactly our minimum
//! supported version.
use crate::cell::SyncUnsafeCell;

// FIXME: move these definitions to libc

#[allow(non_camel_case_types)]
#[repr(C)]
struct os_unfair_lock {
_opaque: u32,
}

const OS_UNFAIR_LOCK_INIT: os_unfair_lock = os_unfair_lock { _opaque: 0 };

extern "C" {
fn os_unfair_lock_lock(lock: *mut os_unfair_lock);
fn os_unfair_lock_trylock(lock: *mut os_unfair_lock) -> bool;
fn os_unfair_lock_unlock(lock: *mut os_unfair_lock);
}

pub struct Mutex {
lock: SyncUnsafeCell<os_unfair_lock>,
}

impl Mutex {
pub const fn new() -> Mutex {
Mutex { lock: SyncUnsafeCell::new(OS_UNFAIR_LOCK_INIT) }
}

pub fn lock(&self) {
unsafe { os_unfair_lock_lock(self.lock.get()) }
}

pub fn try_lock(&self) -> bool {
unsafe { os_unfair_lock_trylock(self.lock.get()) }
}

pub unsafe fn unlock(&self) {
unsafe { os_unfair_lock_unlock(self.lock.get()) }
}
}
8 changes: 8 additions & 0 deletions library/std/src/sys/locks/mutex/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ cfg_if::cfg_if! {
))] {
mod futex;
pub use futex::Mutex;
} else if #[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "watchos",
))] {
mod apple;
pub use apple::Mutex;
} else if #[cfg(target_os = "fuchsia")] {
mod fuchsia;
pub use fuchsia::Mutex;
Expand Down

0 comments on commit 76b3461

Please sign in to comment.