Repository navigation
Description
Motivation
Semaphore::try_acquire_owned, Mutex::try_lock_owned, and RwLock::{try_read_owned, try_write_owned} currently take self: Arc<Self> by value and consume the passed Arc even when acquisition returns None.
In practice, callers hold an Arc<Semaphore> or Arc<Mutex<T>> in shared state—for example, an HTTP gateway enforcing a max_in_flight limit per request and moving the OwnedSemaphorePermit into a response stream:
let Some(permit) = state.permits.clone().try_acquire_owned(1) else {
return service_unavailable();
};When all permits are in flight (available_permits == 0), every rejected request still increments and immediately decrements ArcInner::strong. Because the Arc reference counts share a cache line with Semaphore::available_permits, load shedding under contention turns a read-only check into cross-core cache-line bouncing on ArcInner, slowing down both rejected callers and concurrent OwnedSemaphorePermit drops.
On an Apple M4 Pro (macOS arm64, --release with thin LTO, tested on main at 1cadff0), 1,000,000 failed try_acquire calls per thread on a saturated Semaphore::new(64) show:
| Threads | sem.clone().try_acquire_owned(1) |
Borrow &Arc<Self>, clone only on Some |
|---|---|---|
| 1 | 4.83 ns/op | 0.59 ns/op |
| 8 | 44.83 ns/op | 0.12 ns/op |
Borrowing &Arc<Self> leaves failed calls as a plain Acquire load of available_permits with zero atomic RMWs, keeping the cache line shared across cores.
Proposed change
Before 1.0 (alongside #456), change the fallible owned-try methods to take self: &Arc<Self>—matching the receiver convention already used by pool::unbounded::Pool::try_get(self: &Arc<Self>)—and clone self only after acquiring access:
| Type | Current signature | Proposed signature |
|---|---|---|
Semaphore |
pub fn try_acquire_owned(self: Arc<Self>, permits: usize) -> Option<OwnedSemaphorePermit> |
pub fn try_acquire_owned(self: &Arc<Self>, permits: usize) -> Option<OwnedSemaphorePermit> |
Mutex<T> |
pub fn try_lock_owned(self: Arc<Self>) -> Option<OwnedMutexGuard<T>> |
pub fn try_lock_owned(self: &Arc<Self>) -> Option<OwnedMutexGuard<T>> |
RwLock<T> |
pub fn try_read_owned(self: Arc<Self>) -> Option<OwnedRwLockReadGuard<T>> |
pub fn try_read_owned(self: &Arc<Self>) -> Option<OwnedRwLockReadGuard<T>> |
RwLock<T> |
pub fn try_write_owned(self: Arc<Self>) -> Option<OwnedRwLockWriteGuard<T>> |
pub fn try_write_owned(self: &Arc<Self>) -> Option<OwnedRwLockWriteGuard<T>> |
With self: &Arc<Self>, callers holding sem: Arc<Semaphore> can call sem.try_acquire_owned(1) directly without .clone() at the call site, and only successful acquisitions touch the Arc reference count. The async acquire_owned, lock_owned, read_owned, and write_owned methods can keep self: Arc<Self> since their returned futures own the Arc unconditionally.
Activity