Why is the std::sync::Mutex usually preferred over the tokio one? #7627
Unanswered
WhiteBlackGoose
asked this question in
Q&A
Replies: 1 comment 7 replies
-
This is because the async locking is not free, for example, the async Mutex uses the sync Mutex internally to protect the waker list. So if the lock contention is not significant, the sync Mutex is usually faster. |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone,
we had a chat on the discord server about mutexes, and apparently, the tokio's docs page on Mutex says this:
I'm not sure I understand why the former is a good idea. In particular, using the regular mutex, unlike the async one, blocks the runtime worker instead of just blocking the executing task. With async runtimes normally running on thread pools it might lead to a thread starvation and threads running idle awaiting the mutex.
Here's an easy to imagine scenario:
With an async mutex all tasks hitting the mutex would yield and then rescheduled as the resource is freed, so worker threads will always be doing some useful work.
My feeling is: it's better to use something "safe", i. e. the async mutex, over something that is perhaps less expensive, and only go for the latter if an optimisation is needed (ofc in that case the critical section must be short, bound, and not contain await points).
Please correct me if I'm wrong.
Beta Was this translation helpful? Give feedback.
All reactions