Skip to main content

psync/
par.rs

1//! Phase II's runtime: run the chains of one level of synchronous code on threads.
2//!
3//! [`par_run`] runs its first job on the calling thread and the others on a persistent pool of
4//! parked workers, and returns only when every job has finished. That is what lets the jobs borrow
5//! from the caller's stack frame, as `std::thread::scope` does, at about a tenth of its cost per
6//! job (a parked worker is woken; no thread is created). The pool grows when every worker is busy,
7//! so a job that blocks on I/O never waits for a worker that is itself waiting for it, and past
8//! [`MAX_WORKERS`] a job runs on the calling thread instead.
9//!
10//! The pool is separate from rayon's on purpose: its workers block on I/O, and blocking in rayon's
11//! CPU-sized pool would starve everything else that uses rayon.
12
13extern crate std;
14
15use alloc::boxed::Box;
16use alloc::collections::VecDeque;
17use core::sync::atomic::{AtomicUsize, Ordering};
18use std::sync::{Condvar, Mutex, OnceLock};
19
20/// Past this many workers, jobs run on the thread that asked for them.
21pub const MAX_WORKERS: usize = 256;
22
23type Job = Box<dyn FnOnce() + Send + 'static>;
24
25struct Pool {
26    queue: Mutex<VecDeque<Job>>,
27    ready: Condvar,
28    idle: AtomicUsize,
29    workers: AtomicUsize,
30}
31
32fn pool() -> &'static Pool {
33    static POOL: OnceLock<Pool> = OnceLock::new();
34    POOL.get_or_init(|| Pool {
35        queue: Mutex::new(VecDeque::new()),
36        ready: Condvar::new(),
37        idle: AtomicUsize::new(0),
38        workers: AtomicUsize::new(0),
39    })
40}
41
42impl Pool {
43    /// Queue `job`, waking or starting a worker for it. Gives the job back if the pool is full.
44    fn submit(&'static self, job: Job) -> Result<(), Job> {
45        let mut queue = self.queue.lock().unwrap();
46        // Every queued job needs a worker of its own: a worker may block until a later job runs.
47        if self.idle.load(Ordering::Acquire) <= queue.len() {
48            if self.workers.load(Ordering::Acquire) >= MAX_WORKERS {
49                return Err(job);
50            }
51            self.workers.fetch_add(1, Ordering::AcqRel);
52            std::thread::Builder::new()
53                .name("psync-par".into())
54                .spawn(move || self.work())
55                .expect("psync: could not start a worker thread");
56        }
57        queue.push_back(job);
58        drop(queue);
59        self.ready.notify_one();
60        Ok(())
61    }
62
63    fn work(&'static self) {
64        let mut queue = self.queue.lock().unwrap();
65        loop {
66            if let Some(job) = queue.pop_front() {
67                drop(queue);
68                job();
69                queue = self.queue.lock().unwrap();
70            } else {
71                self.idle.fetch_add(1, Ordering::AcqRel);
72                queue = self.ready.wait(queue).unwrap();
73                self.idle.fetch_sub(1, Ordering::AcqRel);
74            }
75        }
76    }
77}
78
79/// Counts unfinished jobs; [`Latch::wait`] returns when there are none.
80struct Latch {
81    left: Mutex<usize>,
82    done: Condvar,
83}
84
85impl Latch {
86    fn finish(&self) {
87        let mut left = self.left.lock().unwrap();
88        *left -= 1;
89        if *left == 0 {
90            self.done.notify_all();
91        }
92    }
93    fn wait(&self) {
94        let mut left = self.left.lock().unwrap();
95        while *left > 0 {
96            left = self.done.wait(left).unwrap();
97        }
98    }
99}
100
101/// Waits for the pool's jobs even if the caller's own job panics, so no job outlives the
102/// borrows it was given.
103struct WaitOnDrop<'a>(&'a Latch);
104impl Drop for WaitOnDrop<'_> {
105    fn drop(&mut self) {
106        self.0.wait();
107    }
108}
109
110/// A pointer that may cross threads: [`par_run`] guarantees what it points to outlives the job.
111struct SendPtr<T: ?Sized>(*mut T);
112unsafe impl<T: ?Sized> Send for SendPtr<T> {}
113
114/// Run every job, the first on this thread and the rest on the pool, and return when all have
115/// finished. A job that panics on a worker is caught there, and the panic is resumed here after
116/// every job has finished (psync's generated jobs catch their own panics, to replay them in
117/// program order; this is the backstop).
118pub fn par_run(jobs: &mut [&mut (dyn FnMut() + Send)]) {
119    let Some((first, rest)) = jobs.split_first_mut() else {
120        return;
121    };
122    if rest.is_empty() {
123        first();
124        return;
125    }
126    let latch = Latch {
127        left: Mutex::new(rest.len()),
128        done: Condvar::new(),
129    };
130    let panicked: Mutex<Option<Box<dyn core::any::Any + Send>>> = Mutex::new(None);
131    {
132        let _wait = WaitOnDrop(&latch);
133        let mut inline = alloc::vec::Vec::new();
134        for job in rest.iter_mut() {
135            // SAFETY: `_wait` blocks until every submitted job has called `finish`, so the job,
136            // the latch and `panicked` outlive every use of these pointers, even if this thread
137            // panics while running its own job.
138            let job: *mut (dyn FnMut() + Send + '_) = &mut **job;
139            let job: SendPtr<dyn FnMut() + Send + 'static> = SendPtr(unsafe {
140                core::mem::transmute::<
141                    *mut (dyn FnMut() + Send + '_),
142                    *mut (dyn FnMut() + Send + 'static),
143                >(job)
144            });
145            let latch_ptr = SendPtr(&latch as *const Latch as *mut Latch);
146            let panicked_ptr = SendPtr(&panicked as *const _ as *mut Mutex<Option<_>>);
147            let run: Job = Box::new(move || {
148                let (job, latch_ptr, panicked_ptr) = (job, latch_ptr, panicked_ptr);
149                let result = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| unsafe {
150                    (*job.0)()
151                }));
152                unsafe {
153                    if let Err(p) = result {
154                        (*panicked_ptr.0).lock().unwrap().get_or_insert(p);
155                    }
156                    (*latch_ptr.0).finish();
157                }
158            });
159            if let Err(run) = pool().submit(run) {
160                inline.push(run);
161            }
162        }
163        first();
164        for run in inline {
165            run();
166        }
167    }
168    if let Some(p) = panicked.into_inner().unwrap() {
169        std::panic::resume_unwind(p);
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use std::time::{Duration, Instant};
177
178    #[test]
179    fn jobs_borrow_and_overlap() {
180        let (mut a, mut b, mut c) = (0, 0, 0);
181        let start = Instant::now();
182        par_run(&mut [
183            &mut || {
184                std::thread::sleep(Duration::from_millis(50));
185                a = 1
186            },
187            &mut || {
188                std::thread::sleep(Duration::from_millis(50));
189                b = 2
190            },
191            &mut || {
192                std::thread::sleep(Duration::from_millis(50));
193                c = 3
194            },
195        ]);
196        assert_eq!((a, b, c), (1, 2, 3));
197        assert!(
198            start.elapsed() < Duration::from_millis(120),
199            "{:?}",
200            start.elapsed()
201        );
202    }
203
204    #[test]
205    fn nested_jobs_do_not_deadlock() {
206        let mut total = 0;
207        let mut outer: alloc::vec::Vec<usize> = alloc::vec![0; 8];
208        {
209            let mut jobs: alloc::vec::Vec<alloc::boxed::Box<dyn FnMut() + Send + '_>> = outer
210                .iter_mut()
211                .map(|slot| {
212                    alloc::boxed::Box::new(move || {
213                        let (mut x, mut y) = (0, 0);
214                        par_run(&mut [&mut || x = 1, &mut || y = 1]);
215                        *slot = x + y;
216                    }) as alloc::boxed::Box<dyn FnMut() + Send>
217                })
218                .collect();
219            let mut refs: alloc::vec::Vec<&mut (dyn FnMut() + Send)> =
220                jobs.iter_mut().map(|j| &mut **j as _).collect();
221            par_run(&mut refs);
222        }
223        for v in outer {
224            total += v;
225        }
226        assert_eq!(total, 16);
227    }
228
229    #[test]
230    fn a_worker_panic_is_resumed_after_all_jobs() {
231        let mut finished = false;
232        let r = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| {
233            par_run(&mut [
234                &mut || {
235                    std::thread::sleep(Duration::from_millis(20));
236                    finished = true
237                },
238                &mut || panic!("job"),
239            ]);
240        }));
241        assert!(r.is_err());
242        assert!(finished);
243    }
244}