rust-embedded / cortex-m

Low level access to Cortex-M processors
Apache License 2.0
812 stars 145 forks source link

`Mutex::borrow` only gives an immutable reference? #224

Open inodentry opened 4 years ago

inodentry commented 4 years ago

It seems like the cortex_m::interrupt::Mutex type only gives an immutable reference? What's the point of the mutex then? How can I get a mutable reference to the value?

jonas-schievink commented 4 years ago

Mutex makes Send data Sync. You can use cell-based interior mutability inside it.

The reason it is done this way is because the user knows best which cell type to use (eg. RefCell is more costly than Cell but allows obtaining references to the inner value).

Wassasin commented 4 years ago

You can nest two CriticalSections, possibly yielding multiple instances of &mut T if borrow_mut were possible. You can use Mutex<UnsafeCell<T>> and get a mutable reference that way if you take care to never nest the CriticalSections. Even now you can call borrow multiple times concurrently with the same CriticalSection if you so desire. If CriticalSections are not nestable we could perhaps use mutable references to CriticalSections to enforce that your mutex is the only one active. However, this would disallow borrowing from multiple different mutexes at the same time.

Basically Mutex provides a reminder that you have to access the value in a CriticalSection, which ensures single thread access to that variable. In turn this will allow you to safely use cell types, as mentioned earlier.

TDHolmes commented 2 years ago

Related: #208