Expose Mutex in core for targets that don't need OS support

EDIT: My bad, poison::Flag uses std::thread::panicking() so there won't be much code reuse.

This relates to How should we expose atomic load/store on targets that don't support full atomics · Issue #99668 · rust-lang/rust · GitHub in the sense of moving exposing more things in core::sync when feasible. This is also a dependency for Mutex because poison::Flag uses load/store on AtomicBool.

When I look at the implementation of std::sync::Mutex for wasm (and apparently wasi too), it looks like the implementation could actually be in core. It's probably more complicated than for std::sync::atomic because this is an unconditional export from core::sync::atomic, while for std::sync::Mutex it would somehow be conditional.

Is this something that may happen in the future? Or is the Mutex type doomed to be used only from std?

But couldn't core have a version of std::thread::panicking? You can panic without the stdlib (if you set a panic handler). Perhaps core should have something like #[panicking_handler] to set a function that gets called whenever any code calls panicking()?

The only reason wasm's mutex doesn't need OS support right now is that there's no threads. Presumably once wasm threads are added they will be optional and core won't require the APIs that Mutex will use to interact with them.

EDIT: Looking at the code it's using the memory.atomic.wait32 instruction from the threads proposal already. I wonder what the plan is for implementations that don't support that, skimming the threads proposal it doesn't appear to talk about backwards compatibility with implementations that only implement the current core spec.

I think the idea is if a wasm program doesn't support the atomics proposal, then it's guaranteed to be single-threaded. if it supports atomics, then it has wait/notify and can implement mutexes. starting threads requires additional api though, either wasi threads or webworkers or other custom apis

It's been done: #[panic_handler] - The Rustonomicon

But that's a handler for panic!().

I mean literally another handler that checks whether you're in the middle of a panic or not.

std::thread::panicking depends on thread local storage. Thread local storage needs OS support for some targets.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.