cortex-m
cortex-m copied to clipboard
`Mutex::borrow` only gives an immutable reference?
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?
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).
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.
Related: #208