# Reentrant Mutexes in Rust

**URL:** <https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653>\
**Category:** uncategorized\
**Created:** [December 12, 2019, 9:18pm UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653 "2019-12-12T21:18:50Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![matklad](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/matklad/32/41370_2.png) [@matklad](https://users.rust-lang.org/u/matklad)\
**Post date:** [December 12, 2019, 9:18pm UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/1 "2019-12-12T21:18:50Z")

</div>

Moving a conversation in a closed GitHub issue over here...

> The problem is that Rust is so paranoid about data races, that one has to uses mutexes all over the place (if using shared memory) to fight the borrow checker off. This results then in increased risk of deadlocks due to the fact that locks are not reentrant.

> [@havelund](https://github.com/havelund) parking\_lot crate provides reentrant mutex if you need it:  
> [parking\_lot::ReentrantMutex - Rust](https://amanieu.github.io/parking_lot/parking_lot/struct.ReentrantMutex.html)
> 
> I‘m curious what’re the reasons behind not providing reentrant mutex as the default implementation in the standard library?

> I _think_ it's because Mutex and friends were originally meant to be wrappers around the native OS synchronization primitives, and some OS mutexes are not reentrant, though I'm not 100% sure on that.

I'd rather say that rentrant mutexes don't make a ton of sense in Rust most of the time.

The idiomatic Rust API for a mutext is to have a lock method which, given a `&Mutex<T>`, returns an `&mut T` (apropriately wrapped into a guard object). For reentrant mutex, this API doesn't work: you can't return `&mut T` because reentrancy allows one to get the second `&mut T`, violating aliasing guarantees. And `fn lock(&Mutext<T>) -> &T` signature is much less useful, as you naturally _just_ have `&T` if you have `Mutex<T>`. I think it might makes sense when `T: !Sync`, because `ReentrantMutex<T>` maybe can be `Sync` (not sure about this).

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cuviper/32/3156_2.png) [@cuviper](https://users.rust-lang.org/u/cuviper)\
**Post date:** [December 12, 2019, 9:52pm UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/2 "2019-12-12T21:52:43Z")

</div>

> [@matklad](#):
>
> I think it might makes sense when `T: !Sync` , because `ReentrantMutex<T>` maybe can be `Sync` (not sure about this).

Right, in `parking_lot` its `Sync` only requires `T: Send`, which lets you get interior mutability with inner types like `ReentrantMutex<RefCell<T>>`.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [December 13, 2019, 11:49am UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/3 "2019-12-13T11:49:48Z")

</div>

> [@matklad](#):
>
> I'd rather say that rentrant mutexes don't make a ton of sense in Rust most of the time.

This. Rust `&mut` fights _concurrency_, not just _parallelism_. This means that re-entrancy can be just as bad as accessing from multiple threads (if we ignore `!Sync`).

If the control flow is "hidden" behind an abstraction layer (executor etc.) resulting in the re-entrancy being non-trivial, then the code should `try_lock` and handle the failure rather than `lock`ing and hoping there is no deadlock.

> [@cuviper](#):
>
> `ReentrantMutex<RefCell<T>>` .

So the solution here is to rely on `!Sync` to make a difference, which is indeed well spotted. But then I fail to see how `ReentrantMutex<RefCell<T>>` is much different than `RwLock<T>` (two concurrent writers within the same thread deadlock / panic, don't they? I feel like I may be missing an obvious use case...). If it is to be used with `!Sync` and still avoid deadlocks / panics, then, imho, `Cell` ought to be used.

Indeed, `ReentrantMutex<StructWithCellFields>` seems to be the perfect fit for this:

- `ReentrantMutex` allows to have `StructWithCellFields` be _shared_ across threads,

- the `Cell` fields allow reentrancy-safe mutations ("atomic" from the point of view of a single thread).

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cuviper/32/3156_2.png) [@cuviper](https://users.rust-lang.org/u/cuviper)\
**Post date:** [December 14, 2019, 1:05am UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/4 "2019-12-14T01:05:12Z")

</div>

> [@Yandros](#):
>
> But then I fail to see how `ReentrantMutex<RefCell<T>>` is much different than `RwLock<T>` (two concurrent writers within the same thread deadlock / panic, don't they? I feel like I may be missing an obvious use case...). If it is to be used with `!Sync` and still avoid deadlocks / panics, then, imho, `Cell` ought to be used.

If you do see the point with `Cell`, then `RefCell` is just an extension for more complicated types. As long as you keep short-term borrows, it would be useful the same way. Use a scoped `borrow_mut()` for some mutation, then call something potentially reentrant, then `borrow_mut()` again for something else, etc. Plus the `ReentrantMutex` makes the whole operation work atomically at the outermost lock, as far as other threads are concerned.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [December 14, 2019, 5:14pm UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/5 "2019-12-14T17:14:04Z")

</div>

> [@cuviper](#):
>
> If you do see the point with `Cell` , then `RefCell` is just an extension for more complicated types.

True, if one uses a `RefCell` as they would use `Cell` then all is fine 👍

Still, regarding the OP, they were worried about the _potential_ of there being a deadlock (or a panic may I add); and a single `ReentrantMutex<Cell<_>>` is guaranteed to be both panic and deadlock free. Plus, `Cell` has the mental semantics of C/C++ mutation, so it might be more ergonomic for them to work in terms of `Cell` rather than `RefCell`.

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cuviper/32/3156_2.png) [@cuviper](https://users.rust-lang.org/u/cuviper)\
**Post date:** [December 14, 2019, 5:40pm UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/6 "2019-12-14T17:40:00Z")

</div>

Reentrancy is just one form of deadlock. You can still have other issues, like an ABBA deadlock between two threads.

Well, ok, you said a _single_ `ReentrantMutex`... You do have to make sure you don't do anything that would wait on other threads while you hold the lock, like a channel recv, where those other threads might need the lock too.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [March 13, 2020, 5:40pm UTC](https://users.rust-lang.org/t/reentrant-mutexes-in-rust/35653/7 "2020-03-13T17:40:01Z")

</div>

Closed on March 13, 2020, 5:40pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
