Skip to content

Tracking Issue for sync_nonpoison and nonpoison_{condvar,mutex,rwlock} #134645

Open

Description

@tgross35

View all comments

Feature gates:

  • #![feature(sync_nonpoison)]
  • #![feature(nonpoison_condvar)]
  • #![feature(nonpoison_mutex)]
  • #![feature(nonpoison_rwlock)]

This is a tracking issue for versions of synchronization primitives that do not not need to worry about poison.

Public API

sync_nonpoison

The module itself and common types will be gated by this feature:

// std::sync

mod nonpoison {
    pub type TryLockResult<Guard> = Result<Guard, WouldBlock>;
    
    // Error type for failed locking
    pub struct WouldBlock;
}

nonpoison_condvar

// std::sync::nonpoison

pub struct Condvar { /* ... */ }

impl Condvar {
    pub const fn new() -> Self;
    pub fn wait<T>(&self, guard: &mut MutexGuard<'_, T>)
    pub fn notify_one(&self);
    pub fn notify_all(&self);

    pub fn wait_while<T, F>(&self, guard: &mut MutexGuard<'_, T>, mut condition: F)
    where
        F: FnMut(&mut T) -> bool;

    pub fn wait_timeout<T>(
        &self,
        guard: &mut MutexGuard<'_, T>,
        dur: Duration,
    ) -> WaitTimeoutResult;

    pub fn wait_timeout_while<T, F>(
        &self,
        guard: &mut MutexGuard<'_, T>,
        dur: Duration,
        mut condition: F,
    ) -> WaitTimeoutResult
    where
        F: FnMut(&mut T) -> bool;
}

/* trait implementations from `std::sync::poison::Condvar` */

nonpoison_mutex

// std::sync::nonpoison

pub struct Mutex<T: ?Sized> { /* ... */ }

impl<T> Mutex<T> {
    pub const fn new(t: T) -> Self;
}

impl<T: ?Sized> Mutex<T> {
    pub fn lock(&self) -> MutexGuard<'_, T>;
    pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>>;
    pub fn get_mut(&mut self) -> &mut T;
    pub fn into_inner(self) -> T
    where
        T: Sized;
}

/* trait implementations from `std::sync::poison::Mutex` */

pub struct MutexGuard<'a, T: ?Sized + 'a> { /* ... */ }

impl<'a, T: ?Sized> MutexGuard<'a, T> {
    // Unstable API from `mapped_lock_guards`
}

/* trait implementations from `std::sync::poison::MutexGuard` */

// Currently unstable under `mapped_lock_guards`, see that tracking issue for more
pub struct MappedMutexGuard<'a, T: ?Sized + 'a> { /* ... */ }

nonpoison_rwlock

// std::sync::nonpoison

pub struct RwLock<T: ?Sized> { /* ... */ }

impl<T> RwLock<T> {
    pub const fn new(t: T) -> Self;
}

impl<T: ?Sized> RwLock<T> {
    pub fn read(&self) -> RwLockReadGuard<'_, T>;
    pub fn try_read(&self) -> TryLockResult<RwLockReadGuard<'_, T>>;
    pub fn write(&self) -> RwLockWriteGuard<'_, T>;
    pub fn try_write(&self) -> TryLockResult<RwLockWriteGuard<'_, T>>;
    pub fn get_mut(&mut self) -> &mut T;
    pub fn into_inner(self) -> T
    where
        T: Sized;
}

/* trait implementations from `std::sync::poison::RwLock` */

pub struct RwLockReadGuard<'a, T: ?Sized + 'a> { /* private fields */ }

impl<'a, T: ?Sized> RwLockReadGuard<'a, T> {
    // Unstable API from `mapped_lock_guards`
}

/* trait implementations from `std::sync::poison::RwLockReadGuard` */

impl<'a, T: ?Sized> RwLockWriteGuard<'a, T> {
    // Unstable API from `mapped_lock_guards`
}

/* trait implementations from `std::sync::poison::RwLockWriteGuard` */

// Currently unstable under `mapped_lock_guards`, see that tracking issue for more
pub struct MappedRwLockReadGuard<'a, T: ?Sized + 'a> { /* ... */ }
pub struct MappedRwLockReadGuard<'a, T: ?Sized + 'a> { /* ... */ }

Steps / History

Unresolved Questions

Related

Footnotes

  1. https://std-dev-guide.rust-lang.org/feature-lifecycle/stabilization.html ↩

Activity

  1. added
    C-tracking-issue
    T-libs-api
    E-help-wanted
    E-medium
    E-hard
    and removed
    E-medium
    on Dec 22, 2024
  2. changed the title [-]Tracking Issue for `nonpoison_mutex`[/-] [+]Tracking Issue for `nonpoison_mutex` and `sync_poison`[/+] on Dec 22, 2024
  3. changed the title [-]Tracking Issue for `nonpoison_mutex` and `sync_poison`[/-] [+]Tracking Issue for `nonpoison_mutex`[/+] on Dec 22, 2024
  4. changed the title [-]Tracking Issue for `nonpoison_mutex`[/-] [+]Tracking Issue for `sync_nonpoison` and `nonpoison_{condvar,mutex,once,rwlock}`[/+] on Dec 22, 2024
  5. GrigorenkoPV commented on Dec 23, 2024

    @GrigorenkoPV
    Contributor

    Should Barrier, LazyLock, and OnceLock (all of which ignore poison) be moved to std::sync::nonpoison as well (and then unconditionally reexported in std::sync)?

  6. tgross35 commented on Dec 23, 2024

    @tgross35
    MemberAuthor

    I am not sure - for types where we are unlikely to have both versions, it doesn't gain too much. This is also applicable for something like the unstable ReentrantLock (cc @joboet) which is currently nonpoison-only.

    Maybe just leave it as-is for now, I'll add this as an unresolved question.

  7. connortsui20 commented on Jul 19, 2025

    @connortsui20
    Contributor

    @rustbot claim

  8. connortsui20 commented on Jul 20, 2025

    @connortsui20
    Contributor

    Unresolved questions (mainly for Once):

    • Should nonpoison mean all evidence of poison / panicking should be hidden?
    • Does it even make sense for Once to exist in nonpoison when Once supports both poisoning and nonpoisoning (see Tracking issue for std::sync::Once poisoning #33577)?
    • It is not super clear what nonpoison means for Once. The call_once_force method that exists on poison::Once technically "ignores" poison, yet the closure is given a OnceState that tells the caller if the state was poisoned. Should call_once_force be included in a nonpoison::Once?
    • If Once should exist in nonpoison, should the API for [nonpoison::Once] be reduced to just a [call_once] and [wait] method, where they are actually just copies of [poison::Once::call_once_force] and [poison::Once::wait_force]? That makes perfect sense for wait_force -> wait but not for call_once_force -> call_once because of the OnceState mentioned above.

    Personally, I think it makes sense to completely get rid of call_once_force in [nonpoison::Once] and then figure out if it makes sense for [nonpoison::Once::call_once] to pass a OnceState to the closure (which only tells the closure if it is poisoned or not).

  9. added a commit that references this issue on Jul 29, 2025
  10. 58 remaining items

  11. clarfonthey commented on Oct 13, 2026

    @clarfonthey
    Contributor

    Note: our general opinion was that this is going to need deeper investigation into implementation and we're likely not going to stabilize this API as-is. In particular, we probably want someone to take a stab at refactoring the nonpoisoning and poisoning mutexes to use more of the same code, even if they're just wrappers over the same thing.

  12. connortsui20 commented on Oct 13, 2026

    @connortsui20
    Contributor

    @clarfonthey I am happy to give unifying the code a stab (though probably not immediately as I am busy until closer to the end of the month).

    Though I am wondering why the internal implementation is a blocker on the API itself?

  13. clarfonthey commented on Oct 13, 2026

    @clarfonthey
    Contributor

    So, the main reason why is because there are folks who are convinced that we can make the poisoning effectively zero-cost, and you could just choose which to do, in which case we would probably want to combine the APIs and make it just that you choose whether you want poisoning when locking.

    But, such questions would require presenting a working solution for that rather than just guessing.

  14. joboet commented on Oct 15, 2026

    @joboet
    Member

    So, the main reason why is because there are folks who are convinced that we can make the poisoning effectively zero-cost, and you could just choose which to do, in which case we would probably want to combine the APIs and make it just that you choose whether you want poisoning when locking.

    That's only possible on platforms where there are unused bits in the lock state, which is not the case on Windows 7 and on future os_unfair_lock-based Mutex on the Apple platforms.

  15. clarfonthey commented on Oct 22, 2026

    @clarfonthey
    Contributor

    Yes, it is worth noting that this would be "effectively zero-cost" on most platforms, although still cc @nia-e since she was the main proponent of this idea.

  16. connortsui20 commented on Nov 3, 2026

    @connortsui20
    Contributor

    Sorry for the radio silence. I've been experimenting a bit with this, and I wanted to share some of my findings before I propose anything concrete (as the solution space here is not exactly small).

    There seem to be 2 main open questions in this thread:

    1. Can we unify the poison and nonpoison implementations of these 3 locks?
    2. Is it possible to make poisoning zero-cost?

    For 1, there are many ways to share code, but we would want a reasonable (maintainable) implementation. And we also do not want to make a breaking public API change. I think this is definitely possible, and maybe the first step is to unify the existing implementations. But I am hesitant to do that now, especially if a good chunk of the code is going to change due to the next question...

    For 2, it is possible on some platforms to use spare bits for the poisoning flag, but very early and quick experiments on my x86 linux machine showed that packing a poison flag into the futex regressed uncontended lock/mutate/unlock cycles by a median 21% compared to the existing poison mutex implementation. I'm pretty sure this is due to the atomic state gymnastics (can't clear everything to 0 if I have a poison bit set). I would personally say that this large of a regression is unacceptable (again, early benchmarks, but not super encouraging).

    These questions lead to a followup question: If they have shared implementations, and poisoning is actually zero cost, can a single lock type express both behaviors? Even if this is possible, I am not sure this is something we would want from an API design perspective.

    There is also a followup question of how best to represent poisoning as a type. I believe I saw a previous proposal to have a Poison<T> type as a wrapper to make poisoning a composable abstraction. I think this is at odds with the idea that poisoning can be zero-cost w.r.t. space, but if we are willing to relax the zero-cost space constraint, that could potentially be useful.

    Those are some of my high-level findings, and I will continue to experiment. Interested in what people think!

  17. connortsui20 commented on Nov 13, 2026

    @connortsui20
    Contributor

    Ok so I have done a bit more thinking but unfortunately am not able to come to a better conclusion or make progress... So it might be good if there's a bit more discussion on the above.

    @rustbot label +I-libs-nominated

    Again, we can make progress by unifying implementations, but if there are more ambitious plans to both unify the APIs and also make poisoning "free" on certain platforms (and not others) then the unification is probably a waste of time.

  18. added
    I-libs-nominated
    on Nov 13, 2026
  19. clarfonthey commented on Nov 23, 2026

    @clarfonthey
    Contributor

    (Note: was deferred last week's meeting, Nia had some more investigating she wanted to do.)

  20. clarfonthey commented on Nov 24, 2026

    @clarfonthey
    Contributor

    (Note 2: Nia is busy today so she won't be at the meeting, so, I'll just demote this to radar and she can promote back to nominated when she's ready. Hopefully she can be cured of the scourge that is having work to do so that she can get back to work on the real work.)

    @rustbot label -I-libs-nominated +I-libs-radar

  21. added
    I-libs-radar
    and removed
    I-libs-nominated
    on Nov 24, 2026
  22. mitsuhiko commented on Nov 26, 2026

    @mitsuhiko
    Contributor

    Again, we can make progress by unifying implementations, but if there are more ambitious plans to both unify the APIs and also make poisoning "free" on certain platforms (and not others) then the unification is probably a waste of time.

    I have some vested interest in having non poisoning mutexes in the standard library. I did some testing and unfortunately I don't think it's possible to have a Poison<T> type be zero cost but you can have poisoning and non poisoning mutexes share most code without introducing cost by having a policy type internally.

    General slop warning here but I had an agent try a few different approaches for code sharing and I think ultimately it's worth it: https://github.com/mitsuhiko/mutexes

    The basic idea is here: https://github.com/mitsuhiko/mutexes/blob/main/SHARED_IMPL.md

    Internally one adds those types:

    struct Mutex<P, T: ?Sized> { inner: sys::Mutex, poison: P, data: UnsafeCell<T> }
    struct MutexGuard<'a, P: Poison, T: ?Sized> { lock: &'a Mutex<P, T>, poison: P::Guard }
    
    // nonpoison uses P = () and poison uses P = NewType<Atomic<bool>>
    
    trait Poison {
        type Result<G>;      // `G` for (), `LockResult<G>` for Flag
        type Guard: Clone;   // snapshot taken at acquisition: (), or "was panicking"
        type Ptr: Copy;      // mapped guards' way back: (), or NonNull<Flag>
    
        fn check<G>(&self, guard: G) -> Self::Result<G>;           // shared acquire
        fn enter<G>(&self, guard: impl FnOnce(Self::Guard) -> G + Copy) -> Self::Result<G>; // exclusive acquire
        fn leave(&self, guard: &Self::Guard);                      // exclusive release
        fn ptr(&self) -> Self::Ptr;
        unsafe fn leave_ptr(ptr: Self::Ptr, guard: &Self::Guard);  // release, mapped guard
    }
  23. connortsui20 commented on Nov 26, 2026

    @connortsui20
    Contributor

    @mitsuhiko Thanks for looking into this! I think the repo you linked is private though?

    I also have my own robot-generated experiments and I believe I came to a similar conclusion of using an internal generic "policy" type to unify the internal implementations.

    Here's a high-level overview of something similar to what you are proposing (LLM-assisted code disclosure):

    Details

    I think the main difference is that the result type is separate out into the public newtypes.

    trait Policy: Send + Sync + Sized + 'static {
        type Token: Copy + Send + Sync; // "was panicking" at acquisition, or ()
        type Handle: Copy;              // NonNull<Poison> for mapped guards, or ()
    
        const INITIAL: Self;
    
        fn begin() -> Self::Token;
        fn is_poisoned(state: &Self) -> bool;
        fn handle(state: &Self) -> Self::Handle;
        unsafe fn finish(handle: Self::Handle, token: Self::Token);
    }
    
    // P = Poison { failed: AtomicBool } or NoPoison (zero-sized)
    struct Mutex<T: ?Sized, P: Policy> {
        raw: raw::Mutex,
        state: P,
        data: UnsafeCell<T>,
    }
    
    struct MutexGuard<'a, T: ?Sized, P: Policy> {
        lock: &'a Mutex<T, P>,
        token: P::Token,
    }
    
    struct MappedMutexGuard<'a, T: ?Sized, P: Policy> {
        data: NonNull<T>,
        raw: &'a raw::Mutex,
        state: P::Handle,
        token: P::Token,
        marker: PhantomData<&'a mut T>,
    }
    
    // Readers never record poison, so full readers, mapped readers, and
    // `downgrade` all use this one guard type.
    struct RwLockReadGuard<'a, T: ?Sized> {
        data: NonNull<T>,
        inner: &'a raw::RwLock,
    }
    
    // std::sync::poison
    pub struct Mutex<T: ?Sized>(inner::Mutex<T, inner::Poison>);
    
    impl<T: ?Sized> Mutex<T> {
        pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
            let guard = MutexGuard(self.0.acquire());
            check_poison(guard, self.is_poisoned())
        }
    }
    
    // std::sync::nonpoison
    pub struct Mutex<T: ?Sized>(inner::Mutex<T, inner::NoPoison>);
    
    impl<T: ?Sized> Mutex<T> {
        pub fn lock(&self) -> MutexGuard<'_, T> {
            MutexGuard(self.0.acquire())
        }
    }

    I have other prototypes and ideas, but all of them have different tradeoffs and costs. If I have time next week I'll clean everything up and put it in a repo.

    On a separate note, I still believe it is unlikely for poisoning to be zero cost (and as you say, a Poison<T> wrapper is not zero cost in general, for both Poison<Mutex<T> and Mutex<Poison<T>). But if @nia-e's experiments show otherwise, then there is reason to investigate a different API. So basically, I am waiting on those results to continue work on this.

  24. mitsuhiko commented on Nov 26, 2026

    @mitsuhiko
    Contributor

    @connortsui20 sorry for that. I opened it up now. It has all that validation in it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

C-tracking-issueE-hardE-help-wantedI-libs-radarT-libs

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    ⌂ Proxy