5 unstable releases

0.3.1 May 18, 2021
0.3.0 May 14, 2021
0.2.1 Oct 15, 2020
0.2.0 Sep 27, 2020
0.1.0 Jul 21, 2020

#112 in Concurrency

29 downloads per month
Used in 2 crates


811 lines


Rust Crate Rust Documentation


A simple atomic mutex around an Option value which allows synchronized access to a resource.

Rust version 1.49 or greater is currently required.


Licensed under either of

at your option.


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


This crate defines a locking structure wrapping an Option value. The lock can be acquired using a single atomic operation. The OptionLock structure is represented as one atomic u8 variable along with the current value of the lock (which may be empty). It can be constructed in const contexts.

The try_lock and try_take operations are non-blocking and appropriate for using within a polled Future, but the lock cannot register wakers or automatically park the current thread. A traditional Mutex or the async-lock crate may be used in this case.

This structure allows for multiple usage patterns. A basic example (in this case an AtomicI32 could be substituted):

use option_lock::{OptionLock, OptionGuard};

static SHARED: OptionLock<i32> = OptionLock::new(0);

fn try_increase() -> bool {
  if let Ok(mut guard) = SHARED.try_lock() {
    let next = guard.take().unwrap() + 1;
    OptionGuard::replace(&mut guard, next);
  } else {

There are additional examples in the code repository.

This crate uses unsafe code blocks. It is no_std-compatible when compiled without the std feature.


~48K SLoC