Tokio Mutex + std Mutex

Generally is there anything wrong with having an app that uses both std sync Mutex and Tokio Mutex?

As long as you aren't holding a std mutex across an await point, it's perfectly fine to use both.

The benefit of a tokio mutex is that the locking operation requires an await, which means you can have multiple tasks using the same state and they'll be suspended until it's their turn to use the mutex.

The benefits of a std mutex are that it doesn't require an await to access it, meaning you can use the lock from synchronous code. This is particularly useful for things like in-memory caches or interior mutability, where you don't want the caller to know/care that a mutex is being locked.

The ability to choose between both std and tokio mutexes helps deal with the whole "What colour is your function?" problem.


That's what the tokio officially recommends to have.


So lets say I got some code that locks a tokio arc mutex, then calls an async fn with .await, which that function has a datatype which has a chance of locking or being locked by a separate standard sync mutex, could cause a deadlock situation?

I think that depends on how the standard sync mutex is unlocked (i.e. if you wait on something before the sync mutex gets unlocked again). If your sync mutex always gets unlocked right after locking it (without waiting for I/O or any other mutexes or blocking operations), then it should be fine.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.