Skip to content

Replace all tokio::sync::Mutex with std::sync::Mutex where appropriate #9114

@sapphi-red

Description

@sapphi-red

According to the docs of tokio::sync::Mutex, we should be using std::sync::Mutex instead in most places:

Contrary to popular belief, it is ok and often preferred to use the ordinary Mutex from the standard library in asynchronous code.

The feature that the async mutex offers over the blocking mutex is the ability to keep it locked across an .await point. This makes the async mutex more expensive than the blocking mutex, so the blocking mutex should be preferred in the cases where it can be used. The primary use case for the async mutex is to provide shared mutable access to IO resources such as a database connection. If the value behind the mutex is just data, it’s usually appropriate to use a blocking mutex such as the one in the standard library or parking_lot.
https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use

There also a warning in that section:

Note that, although the compiler will not prevent the std Mutex from holding its guard across .await points in situations where the task is not movable between threads, this virtually never leads to correct concurrent code in practice as it can easily lead to deadlocks.
https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use

But these cases can be caught by clippy: https://rust-lang.github.io/rust-clippy/master/index.html#await_holding_lock

related: #9031

Metadata

Metadata

Assignees

Type

Priority

None yet

Effort

None yet

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions