#lazy #cell #once #async

double-checked-cell-async

A thread-safe lazily initialized cell using double-checked locking

1 stable release

2.0.2 Feb 2, 2020

#203 in Asynchronous

Download history 131/week @ 2020-08-07 169/week @ 2020-08-14 99/week @ 2020-08-21 77/week @ 2020-08-28 86/week @ 2020-09-04 180/week @ 2020-09-11 99/week @ 2020-09-18 96/week @ 2020-09-25 140/week @ 2020-10-02 210/week @ 2020-10-09 151/week @ 2020-10-16 148/week @ 2020-10-23 67/week @ 2020-10-30 108/week @ 2020-11-06 120/week @ 2020-11-13 114/week @ 2020-11-20

746 downloads per month
Used in 5 crates (2 directly)

MIT/Apache

17KB
120 lines

async-double-checked-cell

An async fork of double-checked-cell, a thread-safe lazily initialized cell using double-checked locking.

Introduction

Provides a memory location that can be safely shared between threads and initialized at most once. Once the cell is initialized it becomes immutable.

If you do not need to change the value after initialization DoubleCheckedCell<T> is more efficient than a Mutex<Option<T>>.

use double_checked_cell::DoubleCheckedCell;
use futures::future::ready;

let cell = DoubleCheckedCell::new();

// The cell starts uninitialized.
assert_eq!(cell.get().await, None);

// Perform potentially expensive initialization.
let value = cell.get_or_init(async { 21 + 21 }).await;
assert_eq!(*value, 42);
assert_eq!(cell.get().await, Some(&42));

// The cell is already initialized.
let value = cell.get_or_init(async { unreachable!() }).await;
assert_eq!(*value, 42);
assert_eq!(cell.get().await, Some(&42));

Related crates

  • once_cell - Provides a superset of this crate's functionality, with a nicely consistent API.

These crates are similar but distinct by design:

  • lazy-init – Based on a LazyTransform<T, U> which can lazily consume T to produce an U. Therefore cannot support fallible initialization.
  • lazycellAtomicLazyCell does not support lazy initialization (unlike its non-thread-safe counterpart LazyCell using LazyCell::borrow_with()).
  • mitochondria – Not Sync.
  • lazy_static - With the optional (currently nightly only) const_fn feature, DoubleCheckedCell::new() can also be used in static/const context. However lazy_static! is more convenient when there is only a single way to initialize the cell.

Documentation

Read the documentation

Changelog

  • 2.0.2
    • Update to parking_lot 0.9.
  • 2.0.1
    • Update to parking_lot 0.7.
  • 2.0.0
    • Changed unwinding behavior: DoubleCheckedCell no longer implements poisoning.
    • New optional cargo features: parking_lot_mutex, const_fn.
  • 1.1.0
    • Fix unsoundness: DoubleCheckedCell<T> where T: !Send cannot be Sync.
  • 1.0.1
    • Ignore unused_unsafe warning due to UnsafeCell::into_inner() no longer beeing unsafe.
  • 1.0.0
    • Initial release.

License

double-checked-cell is licensed under the Apache 2.0 and MIT license, at your option.

Dependencies

~1–1.6MB
~34K SLoC