Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use consume #71

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions examples/bench.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
#![feature(test)]
use std::mem::size_of;

extern crate test;

use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicUsize, Ordering};

use test::black_box;

const N_THREADS: usize = 32;
const N_ROUNDS: usize = 100_000_000;
const N_THREADS: usize = 4;
const N_ROUNDS: usize = 1_000_000;

static CELL: OnceCell<usize> = OnceCell::new();
static OTHER: AtomicUsize = AtomicUsize::new(0);

fn main() {
let start = std::time::Instant::now();
Expand All @@ -14,15 +21,25 @@ fn main() {
for thread in threads {
thread.join().unwrap();
}
println!("{:?}", OTHER.load(Ordering::Acquire));
println!("{:?}", start.elapsed());
println!("size_of::<OnceCell<()>>() = {:?}", size_of::<OnceCell<()>>());
println!("size_of::<OnceCell<bool>>() = {:?}", size_of::<OnceCell<bool>>());
println!("size_of::<OnceCell<u32>>() = {:?}", size_of::<OnceCell<u32>>());
}

#[inline(never)]
fn thread_main(i: usize) {
let mut data = [0u32; 100];
let mut accum = 0u32;
for _ in 0..N_ROUNDS {
let &value = CELL.get_or_init(|| i);
assert!(value < N_THREADS)
for i in data.iter_mut() {
*i = (*i).wrapping_add(accum);
accum = accum.wrapping_add(3);
}
OTHER.fetch_add(1, Ordering::Relaxed);
black_box(value);
black_box(data);
}
}
35 changes: 35 additions & 0 deletions examples/break_it.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/// Test if the OnceCell properly synchronizes.
/// Needs to be run in release mode.
///
/// We create a `Vec` with `N_ROUNDS` of `OnceCell`s. All threads will walk the `Vec`, and race to
/// be the first one to initialize a cell.
/// Every thread adds the results of the cells it sees to an accumulator, which is compared at the
/// end.
/// All threads should end up with the same result.

use once_cell::sync::OnceCell;

const N_THREADS: usize = 4;
const N_ROUNDS: usize = 1_000_000;

static CELLS: OnceCell<Vec<OnceCell<usize>>> = OnceCell::new();
static RESULT: OnceCell<usize> = OnceCell::new();

fn main() {
CELLS.get_or_init(|| vec![OnceCell::new(); N_ROUNDS]);
let threads =
(0..N_THREADS).map(|i| std::thread::spawn(move || thread_main(i))).collect::<Vec<_>>();
for thread in threads {
thread.join().unwrap();
}
}

fn thread_main(i: usize) {
let cells = CELLS.get().unwrap();
let mut accum = 0;
for cell in cells.iter() {
let &value = cell.get_or_init(|| i);
accum += value;
}
assert_eq!(RESULT.get_or_init(|| accum), &accum);
}
27 changes: 13 additions & 14 deletions src/imp_pl.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use std::{
cell::UnsafeCell,
panic::{RefUnwindSafe, UnwindSafe},
sync::atomic::{AtomicBool, Ordering},
sync::atomic::{AtomicIsize, Ordering},
};

use parking_lot::{lock_api::RawMutex as _RawMutex, RawMutex};

pub(crate) struct OnceCell<T> {
mutex: Mutex,
is_initialized: AtomicBool,
pub(crate) state: AtomicIsize,
pub(crate) value: UnsafeCell<Option<T>>,
}

Expand All @@ -23,30 +23,27 @@ unsafe impl<T: Send> Send for OnceCell<T> {}
impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceCell<T> {}
impl<T: UnwindSafe> UnwindSafe for OnceCell<T> {}

const EMPTY: isize = -1;

impl<T> OnceCell<T> {
pub(crate) const fn new() -> OnceCell<T> {
OnceCell {
mutex: Mutex::new(),
is_initialized: AtomicBool::new(false),
state: AtomicIsize::new(EMPTY),
value: UnsafeCell::new(None),
}
}

/// Safety: synchronizes with store to value via Release/Acquire.
#[inline]
pub(crate) fn is_initialized(&self) -> bool {
self.is_initialized.load(Ordering::Acquire)
}

/// Safety: synchronizes with store to value via `is_initialized` or mutex
/// Safety: synchronizes with store to value via `state` or mutex
/// lock/unlock, writes value only once because of the mutex.
#[cold]
pub(crate) fn initialize<F, E>(&self, f: F) -> Result<(), E>
pub(crate) fn initialize<F, E>(&self, f: F) -> Result<isize, E>
where
F: FnOnce() -> Result<T, E>,
{
let _guard = self.mutex.lock();
if !self.is_initialized() {
let mut state = self.state.load(Ordering::Relaxed);
if state < 0 {
// We are calling user-supplied function and need to be careful.
// - if it returns Err, we unlock mutex and return without touching anything
// - if it panics, we unlock mutex and propagate panic without touching anything
Expand All @@ -59,9 +56,11 @@ impl<T> OnceCell<T> {
let slot: &mut Option<T> = unsafe { &mut *self.value.get() };
debug_assert!(slot.is_none());
*slot = Some(value);
self.is_initialized.store(true, Ordering::Release);
let offset = ((slot as *const _ as usize) - (self as *const _ as usize)) as isize;
self.state.store(offset, Ordering::Release);
state = offset;
}
Ok(())
Ok(state)
}
}

Expand Down
Loading