git clone https://garage44.eu/jeroen/pinnacle.git.. /rt/src/thread.rs
//! Threads of a program, and a pool of them to spread work over the cores.
use crate::{Channel, Received, sys};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicUsize, Ordering};
use pinnacle_abi::{ERROR, call};
const STACK: usize = 256 * 1024;
type Job = Box<dyn FnOnce() + Send>;
extern "C" fn start(job: u64) -> ! {
// SAFETY: `spawn` leaked this box for us to take back.
let job = unsafe { Box::from_raw(job as *mut Job) };
job();
sys::call1(call::EXIT, 0);
unreachable!("exit returned")
}
/// A running thread: `join` waits for it.
pub struct JoinHandle {
done: Channel,
}
impl JoinHandle {
pub fn join(self) {
let mut buffer = [0u8; 8];
let _ = self.done.receive(&mut buffer);
}
}
/// Starts `f` on a thread of this program, on the core with fewest tasks.
pub fn spawn(f: impl FnOnce() + Send + 'static) -> Option<JoinHandle> {
let stack = sys::call1(call::MAP_MEMORY, STACK as u64);
if stack == ERROR {
return None;
}
let (done, tell) = Channel::pair();
let job: Job = Box::new(move || {
f();
tell.send(&[1], Vec::new());
});
let job = Box::into_raw(Box::new(job));
let args = [
start as *const () as u64,
stack + STACK as u64,
job as u64,
0,
0,
0,
0,
];
if sys::call_result(call::THREAD, args).0 == ERROR {
// SAFETY: the thread never started; the box is ours again.
drop(unsafe { Box::from_raw(job) });
return None;
}
Some(JoinHandle { done })
}
/// What a pool's workers share while it runs a batch.
struct Batch {
/// The job function, `jobs` of it to do, by index.
work: *const (dyn Fn(usize) + Sync),
jobs: usize,
next: AtomicUsize,
finished: AtomicUsize,
}
// SAFETY: `work` is Sync and outlives the batch (`run` waits for it).
unsafe impl Sync for Batch {}
unsafe impl Send for Batch {}
/// Workers that run jobs in parallel: the compute device of the CPU. A
/// batch's jobs are taken one at a time from a shared counter, so faster
/// cores take more; the caller works too and returns once all are done.
pub struct Pool {
wake: Vec<Channel>,
done: Channel,
tell: alloc::sync::Arc<Channel>,
}
impl Pool {
/// A pool of `workers` threads besides the caller.
pub fn new(workers: usize) -> Pool {
let (done, tell) = Channel::pair();
let tell = alloc::sync::Arc::new(tell);
let mut wake = Vec::new();
for _ in 0..workers {
let (ours, theirs) = Channel::pair();
let tell = tell.clone();
let started = spawn(move || {
let mut buffer = [0u8; 16];
loop {
match theirs.receive(&mut buffer) {
Received::Message { len: 8, .. } => {
let batch = usize::from_le_bytes(buffer[..8].try_into().unwrap()) as *const Batch;
// SAFETY: `run` keeps the batch alive until every
// worker has said it is done.
work_on(unsafe { &*batch });
tell.send(&[1], Vec::new());
}
_ => return,
}
}
});
if started.is_some() {
wake.push(ours);
}
}
Pool { wake, done, tell }
}
pub fn workers(&self) -> usize {
self.wake.len()
}
/// Runs `work(0) .. work(jobs - 1)` across the workers and the caller.
pub fn run(&self, jobs: usize, work: &(dyn Fn(usize) + Sync)) {
let batch = Batch {
// SAFETY: only the lifetime is erased; `run` outlives the batch.
work: unsafe {
core::mem::transmute::<&(dyn Fn(usize) + Sync), &'static (dyn Fn(usize) + Sync)>(work)
},
jobs,
next: AtomicUsize::new(0),
finished: AtomicUsize::new(0),
};
let pointer = (&raw const batch as usize).to_le_bytes();
for w in &self.wake {
w.send(&pointer, Vec::new());
}
work_on(&batch);
let mut buffer = [0u8; 8];
for _ in 0..self.wake.len() {
let _ = self.done.receive(&mut buffer);
}
let _ = &self.tell;
debug_assert_eq!(batch.finished.load(Ordering::Relaxed), jobs);
}
}
fn work_on(batch: &Batch) {
loop {
let i = batch.next.fetch_add(1, Ordering::Relaxed);
if i >= batch.jobs {
return;
}
// SAFETY: see `Batch`.
unsafe { (*batch.work)(i) };
batch.finished.fetch_add(1, Ordering::Relaxed);
}
}