Why do we need the `Send` constraint here?
⚓ Rust 📅 2026-03-26 👤 surdeus 👁️ 3I'm reading the mara.nl synchronization guide. This excerpt is from the spinlock section:
use std::cell::UnsafeCell;
pub struct SpinLock<T> {
locked: AtomicBool,
value: UnsafeCell<T>,
}
As a precaution,
UnsafeCelldoes not implementSync, which means that our type is now no longer shareable between threads, making it rather useless. To fix that, we need to promise to the compiler that it is actually safe for our type to be shared between threads. However, since the lock can be used to send values of typeTfrom one thread to another, we must limit this promise to types that are safe to send between threads. So, we (unsafely) implementSyncforSpinLock<T>for allTthat implementSend, like this:
unsafe impl<T> Sync for SpinLock<T> where T: Send {}
How can the lock be used to send the wrapped value from one thread to another? It can only move the &mut T between threads, not the actual value, since the SpinLock itself hasn't been declared Send and it owns the wrapped value.
2 posts - 2 participants
🏷️ Rust_feed