Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-sparse/src/pool.rs

//! Worker threads made once and parked between jobs, so a parallel step spawns nothing and
//! allocates nothing: a job is a borrowed closure handed to every worker, and the call
//! returns only when all of them are done with it.

// The one place in the crate that hands a borrowed closure to threads that outlive the
// borrow; `run` waits for every worker before it returns or unwinds (see SAFETY below).
#![allow(unsafe_code)]

use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
use std::sync::atomic::{AtomicU32, AtomicU64};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::{JoinHandle, ThreadId};

/// A borrowed job with its lifetime erased; only `Pool::run` makes one and it outlives no
/// call of `run`.
#[derive(Clone, Copy)]
struct Job(*const (dyn Fn(usize) + Sync + 'static));

// SAFETY: the closure behind the pointer is `Sync`, so calling it from several threads is
// sound; the pointer is only dereferenced while `run` keeps the closure alive.
unsafe impl Send for Job {}

struct State {
    job: Option<Job>,
    /// Workers asked to take part in the current job (ids 1..=wanted).
    wanted: usize,
    /// Bumped once per job, so a worker runs each job once.
    round: u64,
    /// Workers still inside the current job.
    busy: usize,
    panicked: bool,
    quit: bool,
}

struct Shared {
    state: Mutex<State>,
    start: Condvar,
    done: Condvar,
}

fn lock(m: &Mutex<State>) -> MutexGuard<'_, State> {
    // A worker never panics while holding the lock (jobs run outside it), so poisoning
    // cannot leave the state half written.
    m.lock().unwrap_or_else(|p| p.into_inner())
}

/// Where a device runs its parallel jobs: the built-in parked pool by default, or an
/// engine the embedding program already runs (`CpuDevice::with_executor`).
///
/// # Safety
///
/// `run(n, job)` must call `job(t)` exactly once for every `t` in `0..n.min(threads())`
/// (on any threads, the caller included, in any order) and return only after every call
/// has returned. A panic in a call is raised from `run` after the others have finished.
/// The device hands each `t` exclusive pieces of memory on that promise.
pub unsafe trait Executor: Send + Sync {
    /// Threads one job can run on, the caller included (at least 1).
    fn threads(&self) -> usize;

    /// Run `job(t)` for every `t` in `0..n.min(self.threads())` and return when all are
    /// done. A job may call back into its own executor; the inner call then may run all its
    /// shares on the calling thread.
    fn run(&self, n: usize, job: &(dyn Fn(usize) + Sync));

    /// The strong components of the graph whose vertex `v` has the out-neighbours
    /// `adj[off[v]..off[v + 1]]`, an id per vertex (any numbering), when the engine has a
    /// search of its own; `None` (the default) lets kleene run its own.
    fn strong_components(&self, off: &[u64], adj: &[u32]) -> Option<Vec<u32>> {
        let _ = (off, adj);
        None
    }

    /// For every batch of seeds `(vertex, mask)` and every vertex of the same kind of
    /// graph, the OR of the masks of the batch's seeds that reach it (a seed reaches
    /// itself), when the engine has a walk of its own; `None` (the default) lets kleene run
    /// its own. One call takes every batch, so the engine prepares the graph once.
    fn mask_walk(
        &self,
        off: &[u64],
        adj: &[u32],
        batches: &[&[(u32, u64)]],
    ) -> Option<Vec<Vec<u64>>> {
        let _ = (off, adj, batches);
        None
    }

    /// The mask walk where each edge passes only the bits of its set: along the edge at
    /// target slot `j`, a vertex gets the bits of its source's mask that are in set
    /// `slot_set[j]` (`set_words[s * words..(s + 1) * words]`). Masks and seeds are `words`
    /// words each; vertex `v`'s mask is `out[v * words..(v + 1) * words]`. `None` (the
    /// default) lets kleene run its own.
    fn mask_walk_sets(
        &self,
        off: &[u64],
        adj: &[u32],
        slot_set: &[u32],
        set_words: &[u64],
        words: usize,
        seeds: &[(u32, &[u64])],
    ) -> Option<Vec<u64>> {
        let _ = (off, adj, slot_set, set_words, words, seeds);
        None
    }
}

/// Parked worker threads; `run` hands them a job. Dropping the pool stops and joins them.
pub(crate) struct Pool {
    shared: Arc<Shared>,
    /// The thread whose job the workers run, if any: serializes callers (a device shared
    /// by threads). Another caller waits for it ([`Pool::free`]); a call from inside the
    /// running job (its caller or one of the workers) runs alone on its thread.
    gate: Mutex<Option<ThreadId>>,
    free: Condvar,
    workers: Vec<JoinHandle<()>>,
    /// The workers' thread ids.
    worker_ids: Vec<ThreadId>,
}

/// Frees the gate when a job ends, also when it unwinds.
struct Release<'a>(&'a Pool);

impl Drop for Release<'_> {
    fn drop(&mut self) {
        *self.0.gate.lock().unwrap_or_else(|p| p.into_inner()) = None;
        self.0.free.notify_one();
    }
}

impl std::fmt::Debug for Pool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Pool({} workers)", self.workers.len())
    }
}

impl Pool {
    /// A pool of `threads - 1` workers (the caller is the first thread of every job).
    pub(crate) fn new(threads: usize) -> Self {
        let shared = Arc::new(Shared {
            state: Mutex::new(State {
                job: None,
                wanted: 0,
                round: 0,
                busy: 0,
                panicked: false,
                quit: false,
            }),
            start: Condvar::new(),
            done: Condvar::new(),
        });
        let workers = (1..threads.max(1))
            .map(|id| {
                let shared = Arc::clone(&shared);
                std::thread::Builder::new()
                    .name(format!("kleene-{id}"))
                    .spawn(move || worker(id, &shared))
                    .expect("a worker thread could not start")
            })
            .collect::<Vec<JoinHandle<()>>>();
        let worker_ids = workers.iter().map(|w| w.thread().id()).collect();
        Pool {
            shared,
            gate: Mutex::new(None),
            free: Condvar::new(),
            workers,
            worker_ids,
        }
    }
}

// SAFETY: `run` calls every share once (workers take ids `1..n`, the caller 0; a call from
// inside the running job runs `0..n` in turn on its thread) and waits for all of them before it returns or unwinds.
unsafe impl Executor for Pool {
    /// Threads a job can run on (workers and the caller).
    fn threads(&self) -> usize {
        self.workers.len() + 1
    }

    /// Run `f(t)` for every `t` in `0..n` (`n` at most [`Pool::threads`]), `f(0)` on the
    /// calling thread and the others on workers, and return when all are done. A panic in
    /// any of them is raised here after every one has finished.
    fn run(&self, n: usize, f: &(dyn Fn(usize) + Sync)) {
        let n = n.min(self.threads());
        let inline = n <= 1 || {
            let me = std::thread::current().id();
            let mut holder = self.gate.lock().unwrap_or_else(|p| p.into_inner());
            loop {
                match *holder {
                    None => {
                        *holder = Some(me);
                        break false;
                    }
                    // A job calling back into its own device: run here.
                    Some(h) if h == me || self.worker_ids.contains(&me) => break true,
                    // Another caller's job: wait for it, then take the workers.
                    Some(_) => {
                        holder = self.free.wait(holder).unwrap_or_else(|p| p.into_inner());
                    }
                }
            }
        };
        if inline {
            for t in 0..n {
                f(t);
            }
            return;
        }
        let gate = Release(self);
        // SAFETY: the lifetime is erased so workers may hold the pointer, and every use of
        // it ends before this function returns or unwinds: the job is cleared and `busy`
        // reaches 0 (each worker drops its copy before it counts itself out) before the
        // wait below ends, and the caller's own share is run under `catch_unwind` so a
        // panic there waits too.
        let job = Job(unsafe {
            std::mem::transmute::<
                *const (dyn Fn(usize) + Sync + '_),
                *const (dyn Fn(usize) + Sync + 'static),
            >(f as *const _)
        });
        {
            let mut s = lock(&self.shared.state);
            s.job = Some(job);
            s.wanted = n - 1;
            s.busy = n - 1;
            s.round = s.round.wrapping_add(1);
            s.panicked = false;
        }
        self.shared.start.notify_all();
        let mine = catch_unwind(AssertUnwindSafe(|| f(0)));
        let panicked = {
            let mut s = lock(&self.shared.state);
            while s.busy > 0 {
                s = self.shared.done.wait(s).unwrap_or_else(|p| p.into_inner());
            }
            s.job = None;
            s.panicked
        };
        drop(gate);
        if let Err(e) = mine {
            resume_unwind(e);
        }
        if panicked {
            panic!("a kleene worker thread panicked");
        }
    }
}

/// Run `f(t, &mut bufs[t])` for `t` in `0..min(bufs.len(), threads)`, each on its own
/// thread (or all on the caller when the executor is busy).
pub(crate) fn run_each<T: Send>(
    exec: &dyn Executor,
    bufs: &mut [T],
    f: &(dyn Fn(usize, &mut T) + Sync),
) {
    {
        struct Base<T>(*mut T);
        // SAFETY: each thread reaches only its own element through the pointer (below).
        unsafe impl<T: Send> Sync for Base<T> {}
        let n = bufs.len().min(exec.threads());
        let base = Base(bufs.as_mut_ptr());
        let base = &base;
        exec.run(n, &move |t| {
            // SAFETY: `run` calls each `t` in `0..n` exactly once per job (on a worker or,
            // when busy, in turn on the caller), `n <= bufs.len()`, and `bufs` is borrowed
            // mutably for the whole job: the references never overlap.
            let b = unsafe { &mut *base.0.add(t) };
            f(t, b);
        });
    }
}

/// Run `f(t, &mut bufs[t], chunk_t)` for `t` in `0..min(bufs.len(), threads)`, where
/// `chunk_t` is `data[t * per..(t + 1) * per]` (cut at the end of `data`): every thread
/// owns its buffer and its piece of `data`.
pub(crate) fn run_each_chunk<T: Send, U: Send>(
    exec: &dyn Executor,
    bufs: &mut [T],
    data: &mut [U],
    per: usize,
    f: &(dyn Fn(usize, &mut T, &mut [U]) + Sync),
) {
    {
        struct Base<T, U>(*mut T, *mut U, usize);
        // SAFETY: each thread reaches only its own element and its own piece (below).
        unsafe impl<T: Send, U: Send> Sync for Base<T, U> {}
        let n = bufs.len().min(exec.threads());
        let base = Base(bufs.as_mut_ptr(), data.as_mut_ptr(), data.len());
        let base = &base;
        exec.run(n, &move |t| {
            let lo = (t * per).min(base.2);
            let hi = ((t + 1) * per).min(base.2);
            // SAFETY: as in `run_each`, each `t < n <= bufs.len()` runs once per job, so
            // the buffers never overlap; the pieces `lo..hi` of distinct `t` are disjoint
            // and inside `data`, which is borrowed mutably for the whole job.
            let (b, d) = unsafe {
                (
                    &mut *base.0.add(t),
                    std::slice::from_raw_parts_mut(base.1.add(lo), hi - lo),
                )
            };
            f(t, b, d);
        });
    }
}

const _: () = assert!(std::mem::align_of::<u64>() == std::mem::align_of::<AtomicU64>());
const _: () = assert!(std::mem::align_of::<u32>() == std::mem::align_of::<AtomicU32>());

/// Words seen as atomics, so threads may set and clear bits of one bitset together.
pub fn atomic_words(words: &mut [u64]) -> &[AtomicU64] {
    // SAFETY: `AtomicU64` has the size and (checked above) the alignment of `u64`, and the
    // words are borrowed mutably for the life of the result, so nothing reads them other
    // than through the atomics.
    unsafe { &*(words as *mut [u64] as *const [AtomicU64]) }
}

/// Values seen as atomics, so threads may write places of one buffer together (into
/// zeroed memory from `vec![0; n]`, say, whose pages are touched only where written).
pub fn atomic_u32s(values: &mut [u32]) -> &[AtomicU32] {
    // SAFETY: as in `atomic_words`: `AtomicU32` has the size and (checked above) the
    // alignment of `u32`, and the values are borrowed mutably for the life of the result.
    unsafe { &*(values as *mut [u32] as *const [AtomicU32]) }
}

fn worker(id: usize, shared: &Shared) {
    let mut seen = 0u64;
    loop {
        let job = {
            let mut s = lock(&shared.state);
            loop {
                if s.quit {
                    return;
                }
                if s.round != seen {
                    seen = s.round;
                    if id <= s.wanted
                        && let Some(j) = s.job
                    {
                        break j;
                    }
                }
                s = shared.start.wait(s).unwrap_or_else(|p| p.into_inner());
            }
        };
        // SAFETY: `run` keeps the closure alive until this worker counts itself out below.
        let f = unsafe { &*job.0 };
        let ok = catch_unwind(AssertUnwindSafe(|| f(id))).is_ok();
        let mut s = lock(&shared.state);
        if !ok {
            s.panicked = true;
        }
        s.busy -= 1;
        if s.busy == 0 {
            shared.done.notify_all();
        }
    }
}

impl Drop for Pool {
    fn drop(&mut self) {
        lock(&self.shared.state).quit = true;
        self.shared.start.notify_all();
        for w in self.workers.drain(..) {
            let _ = w.join();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn every_share_runs_once_per_job() {
        let pool = Pool::new(4);
        let hits: Vec<AtomicUsize> = (0..4).map(|_| AtomicUsize::new(0)).collect();
        for _ in 0..1000 {
            pool.run(4, &|t| {
                hits[t].fetch_add(1, Ordering::Relaxed);
            });
        }
        pool.run(2, &|t| {
            hits[t].fetch_add(1, Ordering::Relaxed);
        });
        let got: Vec<usize> = hits.iter().map(|h| h.load(Ordering::Relaxed)).collect();
        assert_eq!(got, vec![1001, 1001, 1000, 1000]);
    }

    #[test]
    fn a_second_caller_waits_for_the_first_and_gets_the_workers() {
        let pool = Pool::new(4);
        let (tx, rx) = std::sync::mpsc::channel();
        let ids = Mutex::new(Vec::new());
        std::thread::scope(|sc| {
            sc.spawn(|| {
                pool.run(4, &|t| {
                    if t == 0 {
                        tx.send(()).expect("the other caller waits");
                        std::thread::sleep(std::time::Duration::from_millis(100));
                    }
                })
            });
            rx.recv().expect("the first job runs");
            pool.run(4, &|_| {
                ids.lock()
                    .unwrap_or_else(|p| p.into_inner())
                    .push(std::thread::current().id());
            });
        });
        let mut ids = ids.into_inner().unwrap_or_else(|p| p.into_inner());
        ids.sort_unstable_by_key(|id| format!("{id:?}"));
        ids.dedup();
        assert_eq!(ids.len(), 4, "the second job ran on every thread");
    }

    #[test]
    fn a_job_that_calls_back_in_runs_alone_and_a_panic_reaches_the_caller() {
        let pool = Pool::new(3);
        let n = AtomicUsize::new(0);
        pool.run(3, &|_| {
            pool.run(3, &|_| {
                n.fetch_add(1, Ordering::Relaxed);
            });
        });
        assert_eq!(n.load(Ordering::Relaxed), 9);
        let r = catch_unwind(AssertUnwindSafe(|| {
            pool.run(3, &|t| assert!(t != 2, "boom"));
        }));
        assert!(r.is_err());
        // The pool still works afterwards.
        pool.run(3, &|_| {
            n.fetch_add(1, Ordering::Relaxed);
        });
        assert_eq!(n.load(Ordering::Relaxed), 12);
    }
}