Crates.io | double-checked-cell-async |
lib.rs | double-checked-cell-async |
version | 2.0.2 |
source | src |
created_at | 2020-02-02 15:53:53.266043 |
updated_at | 2020-02-02 15:53:53.266043 |
description | A thread-safe lazily initialized cell using double-checked locking |
homepage | |
repository | https://github.com/chrislearn/double-checked-cell-async |
max_upload_size | |
id | 204238 |
size | 30,413 |
An async fork of double-checked-cell, a thread-safe lazily initialized cell using double-checked locking.
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));
These crates are similar but distinct by design:
LazyTransform<T, U>
which can lazily consume T
to produce an U
. Therefore cannot support fallible initialization.AtomicLazyCell
does not support lazy initialization (unlike its non-thread-safe counterpart LazyCell
using LazyCell::borrow_with()
).Sync
.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.DoubleCheckedCell
no longer implements
poisoning.parking_lot_mutex
, const_fn
.DoubleCheckedCell<T>
where T: !Send
cannot be Sync
.unused_unsafe
warning due to UnsafeCell::into_inner()
no longer
beeing unsafe.double-checked-cell is licensed under the Apache 2.0 and MIT license, at your option.