embassy icon indicating copy to clipboard operation
embassy copied to clipboard

Add non-reentrant variant of blocking mutex

Open FeldrinH opened this issue 5 months ago • 1 comments

Currently, the async mutex is non-reentrant, but the blocking mutex is reentrant. In practice, I find the reentrant mutex to be annoying and clunky to use, because you almost always need a RefCell around the value to do anything useful with it.

It would be nice if there was a non-reentrant variant of the blocking mutex which provided mutable access to the locked value. I imagine that in practice 95% of blocking mutex uses would use that over the non-reentrant variant. This would have the following benefits:

  • More ergonomic. No need to add a RefCell and call borrow_mut on it every time.
  • More consistent. Both the async and blocking mutex would be non-reentrant, avoiding any confusion and refactoring when swapping between them.
  • Smaller memory footprint (and maybe slightly better performance): RefCell uses a whole isize to track its reference count. A non-reentrant mutex could get away with a single bool saving some memory. Also, avoiding the increments and decrements done to maintain RefCell reference count might improve performance slightly (or it might not, hard to say for sure). These are small differences, but on embedded platforms I think they are at least worth noting.

FeldrinH avatar Dec 02 '25 15:12 FeldrinH

There is https://docs.embassy.dev/embassy-sync/git/default/blocking_mutex/struct.Mutex.html#method.lock_mut that you could use. It's unsafe specifically because the API cannot guarantee non-reentrancy.

lulf avatar Dec 04 '25 12:12 lulf