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

Cleanup #3

Merged
merged 3 commits into from
Sep 14, 2024
Merged
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
35 changes: 19 additions & 16 deletions src/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{
cell::{Cell, UnsafeCell},
mem::ManuallyDrop,
panic::{self, AssertUnwindSafe},
ptr::{self, NonNull},
ptr::NonNull,
sync::atomic::{AtomicU8, Ordering},
thread::{self, Thread},
};
Expand Down Expand Up @@ -111,7 +111,7 @@ impl<F> JobStack<F> {
}

/// It should only be called once.
pub unsafe fn take_once(self) -> F {
pub unsafe fn take_once(&self) -> F {
// No `Job` has has been executed, therefore `self.f` has not yet been
// `take`n.
unsafe { ManuallyDrop::take(&mut *self.f.get()) }
Expand All @@ -124,8 +124,8 @@ impl<F> JobStack<F> {
/// thread boundaries.
#[derive(Clone, Debug)]
pub struct Job<T = ()> {
stack: *const JobStack,
harness: unsafe fn(&mut Scope<'_>, *const JobStack, *const Future),
stack: NonNull<JobStack>,
harness: unsafe fn(&mut Scope<'_>, NonNull<JobStack>, NonNull<Future>),
prev: Cell<Option<NonNull<Self>>>,
fut_or_next: Cell<Option<NonNull<Future<T>>>>,
}
Expand All @@ -137,25 +137,28 @@ impl<T> Job<T> {
T: Send,
{
/// It should only be called while the `stack` is still alive.
unsafe fn harness<F, T>(scope: &mut Scope<'_>, stack: *const JobStack, fut: *const Future)
where
unsafe fn harness<F, T>(
scope: &mut Scope<'_>,
stack: NonNull<JobStack>,
fut: NonNull<Future>,
) where
F: FnOnce(&mut Scope<'_>) -> T + Send,
T: Send,
{
// The `stack` is still alive.
let stack = unsafe { &*(stack as *const JobStack<F>) };
// This is the first call to `take` the closure since
let stack: &JobStack<F> = unsafe { stack.cast().as_ref() };
// This is the first call to `take_once` the closure since
// `Job::execute` is called only after the job has been popped.
let f = unsafe { ManuallyDrop::take(&mut *stack.f.get()) };
let f = unsafe { stack.take_once() };
// Before being popped, the `JobQueue` allocates and store a
// `Future` in `self.fur_or_next` that should get passed here.
let fut = unsafe { &*(fut as *const Future<T>) };
let fut: &Future<T> = unsafe { fut.cast().as_ref() };

fut.complete(panic::catch_unwind(AssertUnwindSafe(|| f(scope))));
}

Self {
stack: stack as *const JobStack<F> as *const JobStack,
stack: NonNull::from(stack).cast(),
harness: harness::<F, T>,
prev: Cell::new(None),
fut_or_next: Cell::new(None),
Expand Down Expand Up @@ -188,7 +191,7 @@ impl<T> Job<T> {
self.fut_or_next.get().and_then(|fut| {
// Before being popped, the `JobQueue` allocates and stores a
// `Future` in `self.fur_or_next` that should get passed here.
let result = unsafe { (*fut.as_ptr()).wait() };
let result = unsafe { fut.as_ref().wait() };
// We only can drop the `Box` *after* waiting on the `Future`
// in order to ensure unique access.
unsafe {
Expand Down Expand Up @@ -219,7 +222,7 @@ impl Job {
// Before being popped, the `JobQueue` allocates and store a
// `Future` in `self.fur_or_next` that should get passed here.
unsafe {
(self.harness)(scope, self.stack, self.fut_or_next.get().unwrap().as_ptr());
(self.harness)(scope, self.stack, self.fut_or_next.get().unwrap());
}
}
}
Expand All @@ -235,7 +238,7 @@ pub struct JobQueue {
impl Default for JobQueue {
fn default() -> Self {
let root = Box::leak(Box::new(Job {
stack: ptr::null(),
stack: NonNull::dangling(),
harness: |_, _, _| (),
prev: Cell::new(None),
fut_or_next: Cell::new(None),
Expand Down Expand Up @@ -357,15 +360,15 @@ mod tests {
impl Job {
pub fn from_usize(val: &'static usize) -> Self {
Self {
stack: val as *const usize as *mut JobStack as *const JobStack,
stack: NonNull::from(val).cast(),
harness: |_, _, _| (),
prev: Cell::new(None),
fut_or_next: Cell::new(None),
}
}

pub fn as_usize(&self) -> usize {
unsafe { *(self.stack as *const usize) }
unsafe { *self.stack.cast().as_ref() }
}
}

Expand Down
32 changes: 21 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,34 +590,44 @@ mod tests {
}
}

fn increment(s: &mut Scope, slice: &mut [ThreadId], id: ThreadId) {
fn increment(s: &mut Scope, slice: &mut [u32], id: ThreadId) -> bool {
let mut threads_crossed = AtomicBool::new(false);

match slice.len() {
0 => (),
1 => slice[0] += 1,
_ => {
let (head, tail) = slice.split_at_mut(1);
let (_, tail) = slice.split_at_mut(1);

s.join(
|_| {
thread::sleep(Duration::from_micros(10));
thread::sleep(Duration::from_micros(100));

let current_id = thread::current().id();
head[0] = current_id;

if current_id != id {
if thread::current().id() != id {
threads_crossed.store(true, Ordering::Relaxed);
panic!("panicked across threads");
}
},
|s| increment(s, tail, id),
);
}
}

*threads_crossed.get_mut()
}

let mut vals = [thread::current().id(); 10];
let mut vals = [0; 10];

increment(&mut threat_pool.scope(), &mut vals, thread::current().id());
let threads_crossed =
increment(&mut threat_pool.scope(), &mut vals, thread::current().id());

// Just in case this test fails.
panic!("thread IDs: {:?}", vals);
// Since there was no panic up to this point, this means that the
// thread boundary has not been crossed.
//
// Check that the work was done and pass the testt artificially.
if !threads_crossed {
assert_eq!(vals, [1; 10]);
panic!("panicked across threads");
}
}
}