Skip to content

Prefer tokio::sync::RwLock and tokio::sync::Mutex over parking_lot ones in async functions #88

@kgrech

Description

@kgrech

Is your feature request related to a problem? Please describe.
Tokio async runtime provides async version of RwLock and Mutex. When we are inside the async method, we should prefer using them instead of using sync implementations.
There are 2 reasons for it:

  • If you try to lock synchronous lock or mutex, you block the entire thread. There is no way for the reactor to perform a context switch and start to perform another async function while the required resource is occupied.
    It inlines with the general rule of async rust: no blocking calls in async functions.
  • In certain cases the async API would accept not just Future trait, but Future + Send trait. This is quite often, the example could be tokio::spawn API. In a situation like below
let mut update_handler = removed.update_handler.lock(); // sync lock here, block the whole thread
update_handler.wait_worker_stops().await?;

the resulting feature (the async function calling these 2 lines) would NOT implement Send trait as synchronous MutexGuard obtained by lock method does not implement Send trait (the async one does). This would limit us on usage of the async method in such cases. Coming to practice now: the tonic grpc framework I use to implement its services with async functions which are required to implement Send trait and usage of the above lock is a blocker for it.

Describe the solution you'd like
Use async locks and mutex the locks which are only used in async methods

pub update_handler: Arc<tokio::sync::Mutex<UpdateHandler>>,
..
let mut update_handler = removed.update_handler.lock().await; //If resource is busy, reactor can run another future while current async function waits
update_handler.wait_worker_stops().await?;

Describe alternatives you've considered
We could keep existing implementation, however, it is likely less efficient and would block us with grpc additions.

Additional context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions