#futures #async #future #tokio #mutex

nightly tokio-lk

Futures-aware lock-by-id primitives

5 releases

0.2.2 Mar 26, 2020
0.2.1 Mar 26, 2020
0.1.3 Mar 17, 2020

#325 in Asynchronous

31 downloads per month

MIT license

674 lines

Crates.io License Build Status

tokio-lk version - 0.2.2


** A lock-by-id future for tokio **

Lock future will return Guard once it gets the mutex. to hold the lock in subsequent futures, move the Guard inside the future output. to release the mutex, simply drops the Guard from your future chain.

Each Lock object is assigned an unique id. The uniqueness is promised until USIZE_MAX of id gets generated. Make sure old Locks are dropped before you generate new Locks above this amount.


  • 0.2.2 - minor fix on cargo.toml to let docs.rs generate documentation of all features
  • 0.2.1 - add features for using either hashbrown or dashmap. add KeyPool for hashmap abstraction.
  • 0.2.0 - bump to futures 0.3 and tokio 0.2
  • 0.1.3 - now depends on dashmap to replace RwLock<HashMap>
  • 0.1.2 - first stable version


use std::time::{Duration, Instant};
use tokio_lk::*;
use futures::prelude::*;
use tokio::runtime::Runtime;
use tokio::time::delay_for;

let mut rt = Runtime::new().unwrap();
let map = KeyPool::<MapType>::new();
let now = Instant::now();
// this task will compete with task2 for lock at id 1
let task1 = async {
    let _guard = Lock::fnew(1, map.clone()).await.await;
// this task will compete with task1 for lock at id 1
let task2 = async {
    let _guard = Lock::fnew(1, map.clone()).await.await;
// no other task compete for lock at id 2
let task3 = async {
    let _guard = Lock::fnew(2, map.clone()).await.await;
rt.block_on(async { tokio::join!(task1, task2, task3) });


  • hashbrown
    • provides MapType as a type alias of hashbrown::HashMap for KeyPool initialization
  • dashmap
    • provides DashMapType as a type alias of dashmap::DashMap for KeyPool initialization
  • default: hashbrown
  • all: both hashbrown and dashmap


to run the benchmark, execute the following command in the prompt:

cargo bench -- --nocapture

The lock1000_parallel benchmark is to run 1000 futures locked by a single lock to update the counter. The lock1000_serial benchmark is to run run similar operations in a single thread. Currently our implementation is about 4~5 times slower than the single threaded version.


Licensed under


Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, shall be licensed as above, without any additional terms or conditions.


~80K SLoC