futures_locks/
lib.rs

1// vim: tw=80
2
3//!  A library of [`Futures`]-aware locking primitives.  These locks can safely
4//!  be used in asynchronous environments like [`Tokio`].  When they block,
5//!  they'll only block a single task, not the entire reactor.
6//!
7//!  These primitives generally work much like their counterparts from the
8//!  standard library.  But instead of blocking, they return a `Future` that
9//!  completes when the lock has been acquired.
10//!
11//! # Examples
12//!
13//! ```
14//! # use futures_locks::*;
15//! # use futures::executor::block_on;
16//! # use futures::{Future, FutureExt};
17//! # fn main() {
18//! let mtx = Mutex::<u32>::new(0);
19//! let fut = mtx.lock().map(|mut guard| { *guard += 5; });
20//! block_on(fut);
21//! assert_eq!(mtx.try_unwrap().unwrap(), 5);
22//! # }
23//! ```
24//!
25//! [`Futures`]: https://github.com/rust-lang-nursery/futures-rs
26//! [`Tokio`]: https:/tokio.rs
27
28#![cfg_attr(docsrs, feature(doc_cfg))]
29#![warn(missing_docs)]
30
31mod mutex;
32mod rwlock;
33
34pub use mutex::{Mutex, MutexFut, MutexGuard, MutexWeak};
35pub use rwlock::{RwLock, RwLockReadFut, RwLockWriteFut,
36                 RwLockReadGuard, RwLockWriteGuard};
37
38use futures_channel::oneshot;
39use std::{error, fmt};
40
41/// Poll state of all Futures in this crate.
42enum FutState {
43    New,
44    Pending(oneshot::Receiver<()>),
45    Acquired
46}
47
48/// The lock could not be acquired at this time because the operation would
49/// otherwise block.
50#[derive(Clone, Copy, Debug)]
51pub struct TryLockError;
52
53impl fmt::Display for TryLockError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(f, "try_lock failed because the operation would block")
56    }
57}
58
59impl error::Error for TryLockError {}