Drop handler, tokio::sync::Mutex, async

Are the following statements correct ?

  1. drop handlers can't be async

  2. async code should use tokio:::sync::Mutex instead of std::sync::Mutex (so that waiting on a lock blocks an async task, not an OS thread)

  3. locking a tokio::sync::Mutex in a drop handler is not possible (forces the drop handler to be async)

===

Therefore, if there is a Mutex that we want to use both in async code and in a drop handler, we have two suboptimal choices:

  1. make the Mutex a std::sync => suboptimal because the async code will then block an OS thread instead of an async task

  2. make the Mutex a tokio::sync => suboptimal because the drop handler will probably have to do some type of spawn/block_on to execute an async block to deal with the tokio::sync::Mutex

Is there a clean solution to this problem ?

No.

https://docs.rs/tokio/latest/tokio/sync/struct.Mutex.html#which-kind-of-mutex-should-you-use

1 Like