Why does T need to be Send for a Mutex to be Sync

50 points Lochlanna

I've been playing around developing my own mutex recently. I'm using the lock\_api crate to wrap my raw mutex and provide the nice user friendly interface.

I was looking at the code for mutex within lock\_api and noticed something that doesn't make sense to me. For the lock to be Sync, T must implement Send which seems odd to me as the inner data isn't being sent across threads. Just a reference to it.

The code in question looks like (link to source on GitHub)

pub struct Mutex<R, T: ?Sized> {
    raw: R,
    data: UnsafeCell<T>,
}
unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<R, T> {}
unsafe impl<R: RawMutex + Sync, T: ?Sized + Send> Sync for Mutex<R, T> {}

Where I would have expected it to be

pub struct Mutex<R, T: ?Sized> {
    raw: R,
    data: UnsafeCell<T>,
}
unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<R, T> {}
unsafe impl<R: RawMutex + Sync, T: ?Sized> Sync for Mutex<R, T> {}

What am I missing here?