cortex-m icon indicating copy to clipboard operation
cortex-m copied to clipboard

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

Open inodentry opened this issue 4 years ago • 3 comments

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?

inodentry avatar Jun 08 '20 11:06 inodentry

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).

jonas-schievink avatar Jun 08 '20 11:06 jonas-schievink

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.

Wassasin avatar Jun 09 '20 11:06 Wassasin

Related: #208

TDHolmes avatar Dec 15 '21 20:12 TDHolmes