| Crates.io | wasm_safe_mutex |
| lib.rs | wasm_safe_mutex |
| version | 0.1.2 |
| created_at | 2025-08-18 03:23:53.830982+00 |
| updated_at | 2025-11-28 10:37:10.700463+00 |
| description | A suite of WebAssembly-safe synchronization primitives that paper over platform-specific locking constraints. |
| homepage | https://sealedabstract.com/code/wasm_safe_mutex |
| repository | https://github.com/drewcrawford/wasm_safe_mutex |
| max_upload_size | |
| id | 1799906 |
| size | 310,131 |

A suite of WebAssembly-safe synchronization primitives that paper over platform-specific locking constraints.
WebAssembly's main thread cannot use blocking locks - attempting to do so will panic with "cannot block on the main thread". This is a fundamental limitation of the browser environment where blocking the main thread would freeze the entire UI.
However, blocking locks ARE allowed in:
Atomics.wait is available)This crate provides synchronization primitives that automatically adapt their locking strategy based on the runtime environment:
thread::park)Atomics.wait when availableThis means you can write code once and have it work correctly across all platforms, without worrying about whether you're on the main thread, a worker thread, native or WASM.
This crate provides the following primitives, all of which support the adaptive behavior:
Mutex: A mutual exclusion primitive for protecting shared data.RwLock: A reader-writer lock that allows multiple concurrent readers or one exclusive writer.Condvar: A condition variable for blocking a thread while waiting for an event.mpsc: A multi-producer, single-consumer channel for message passing.Add this to your Cargo.toml:
[dependencies]
wasm_safe_mutex = "0.1.0"
use wasm_safe_mutex::Mutex;
let mutex = Mutex::new(42);
let mut guard = mutex.lock_sync();
*guard = 100;
drop(guard);
assert_eq!(*mutex.lock_sync(), 100);
use wasm_safe_mutex::rwlock::RwLock;
let rwlock = RwLock::new(vec![1, 2, 3]);
// Multiple readers
let r1 = rwlock.lock_sync_read();
let r2 = rwlock.lock_sync_read();
assert_eq!(r1.len(), 3);
assert_eq!(r2.len(), 3);
drop(r1);
drop(r2);
// Exclusive writer
let mut w = rwlock.lock_sync_write();
w.push(4);
use wasm_safe_mutex::Mutex;
let mutex = Mutex::new(0);
// Async lock works everywhere, including WASM main thread
let mut guard = mutex.lock_async().await;
*guard += 1;
The primitives transparently handle platform differences:
Atomics.waitThis automatic adaptation means your code works everywhere without modification.