#tokio #lock #locking #task #single-thread

tokio-lock

Access an object from a single Tokio task

5 releases (3 stable)

✓ Uses Rust 2018 edition

1.1.0 Feb 17, 2019
1.0.1 Feb 17, 2019
0.2.0-dev Feb 17, 2019
0.1.0-dev Feb 17, 2019

#263 in Asynchronous

Download history 20/week @ 2019-11-01 18/week @ 2019-11-08 25/week @ 2019-11-15 22/week @ 2019-11-22 16/week @ 2019-11-29 42/week @ 2019-12-06 14/week @ 2019-12-13 2/week @ 2019-12-20 7/week @ 2019-12-27 28/week @ 2020-01-03 33/week @ 2020-01-10 35/week @ 2020-01-17 43/week @ 2020-01-24 34/week @ 2020-01-31 22/week @ 2020-02-07

97 downloads per month

MIT license

11KB
191 lines

tokio-lock

Build Status Latest version Documentation License

Access an object from a single Tokio task.

Why?

Tokio futures run in a multi-threaded environment, which makes accessing an object from different futures complicated. In many cases, however, the object is not thread safe, and has to be accessed from a single thread.

As an example, imagine writing HTTP wrapper for an RPC server. Most likely, this has to be done either with a MPSC (multiple producer single consumer) queue and a large enum of possible messages, or with a mutex guarding access to the object.

This library creates a convenient abstraction on top of MPSC, that is managed internally.

Quick example

extern crate futures;
extern crate tokio;
extern crate tokio_lock;

use futures::prelude::*;
use futures::future::{self, FutureResult};

use tokio_lock::{Lock, Error};

// Create a Lock instance
let mut lock = Lock::new();

struct TestObject {
    field: u32,
}

// Create a future that is going to manage the `TestObject` instance.
// NOTE: Object is consumed in the process.
let manage = lock.manage(TestObject { field: 42 });

// Borrow an object from `lock` and execute given closure.
let get_field = lock.get(|obj| -> FutureResult<u32, Error> {
    future::ok(obj.field)
}).map(move |field| {
    assert_eq!(field, 42);

    // Stop managing the object
    // NOTE: This may not be needed in the most of the cases.
    lock.stop();
});

// NOTE: `manage` is a future and has to be run
tokio::run(manage.join(get_field).map_err(|err| {
    panic!("Got error");
}).map(|_| ()));

Using tokio-lock

Please check our documentation for details.

Dependencies

~1.5MB
~23K SLoC