Skip to main content

mln_engine/exec/
pool.rs

1//! Where background work runs: a [`Pool`] of worker threads, and the
2//! [`TaskGroup`]s of its tasks that an owner waits for.
3//!
4//! A pool's tasks queue in lanes: the pool's own, and one per group. Its
5//! workers take one task from each lane with work in turn, so a lane with
6//! many tasks queued doesn't hold back the tasks of the others. A serial
7//! group's lane ([`TaskGroup::serial`]) runs one task at a time, in order.
8//!
9//! A pool without threads ([`Pool::local`]) is for a host with one thread,
10//! the browser: its tasks run when that thread calls [`Pool::run_until`].
11
12use std::collections::VecDeque;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::thread::ThreadId;
16
17use parking_lot::{Condvar, Mutex};
18
19#[cfg(not(target_family = "wasm"))]
20#[cfg(not(target_family = "wasm"))]
21use crate::exec::thread::Joined;
22
23/// A task that runs on a pool.
24pub(crate) type Task = Box<dyn FnOnce() + Send + 'static>;
25
26/// What a pool calls when work arrives while it had none.
27pub(crate) type Waker = Arc<dyn Fn() + Send + Sync>;
28
29/// What a pool calls with the message of a task's panic.
30pub(crate) type PanicHandler = Arc<dyn Fn(String) + Send + Sync>;
31
32/// Where a job hands its result: called at most once, from any thread,
33/// while the job runs or later. Dropping it uncalled drops the result.
34pub(crate) type Respond<R> = Box<dyn FnOnce(R) + Send>;
35
36/// Runs background work on worker threads, or, without threads, on the
37/// thread that runs it. Cheap to clone: clones share the pool. A worker
38/// starts when a task arrives while every running worker is busy, up to the
39/// pool's thread count, so a pool that runs nothing starts no threads. Its
40/// threads end once the last clone and the last [`TaskGroup`] of it drop, or
41/// once it's [`shut_down`](Self::shut_down), dropping the tasks still
42/// queued.
43#[derive(Clone)]
44pub struct Pool {
45    workers: Arc<Workers>,
46}
47
48/// A lane of tasks of one pool, which an owner waits for with
49/// `wait`. Cheap to clone: clones share the lane. Dropping it
50/// leaves its queued tasks to run.
51///
52/// A [`serial`](Self::serial) group runs at most one of its tasks at a time,
53/// in the order they were spawned.
54#[derive(Clone)]
55pub struct TaskGroup {
56    pool: Pool,
57    lane: Arc<Lane>,
58}
59
60/// The pool's threads, which stop when this drops.
61struct Workers {
62    shared: Arc<Shared>,
63}
64
65struct Shared {
66    ring: Mutex<Ring>,
67    /// Signalled when a lane joins the ring, or the pool stops.
68    work: Condvar,
69    /// The pool's own lane, for [`Pool::spawn`].
70    lane: Arc<Lane>,
71    waker: Mutex<Option<Waker>>,
72    panic_handler: Mutex<Option<PanicHandler>>,
73    /// The most worker threads the pool starts: none for a local pool.
74    max_threads: usize,
75    /// The workers started so far.
76    threads: Mutex<Threads>,
77    /// Whether the pool stopped. Set under the ring's lock, which the workers
78    /// wait on, and read without it by threads that hold a lane's lock.
79    stopped: AtomicBool,
80}
81
82#[derive(Default)]
83struct Threads {
84    #[cfg(not(target_family = "wasm"))]
85    joined: Vec<Joined>,
86    ids: Vec<ThreadId>,
87}
88
89/// The lanes that may start a task, each once, in the order the workers
90/// visit them. A lane may also be here for a while after it can no longer
91/// start one (a waiting thread took its task); the workers drop it then.
92#[derive(Default)]
93struct Ring {
94    lanes: VecDeque<Arc<Lane>>,
95    /// The workers started, or starting.
96    started: usize,
97    /// The workers waiting for a task.
98    idle: usize,
99}
100
101#[derive(Default)]
102struct Lane {
103    state: Mutex<LaneState>,
104    /// Signalled when one of the lane's tasks ends.
105    ended: Condvar,
106}
107
108#[derive(Default)]
109struct LaneState {
110    tasks: VecDeque<Task>,
111    running: usize,
112    /// Whether the lane runs one task at a time. Fixed when it's made.
113    serial: bool,
114    /// Whether the lane is in the ring, or the thread that set this is about
115    /// to put it there.
116    ///
117    /// The lane's invariant: whenever its lock is released, a lane that
118    /// [`may_start`](Self::may_start) a task has this set. Whatever makes a
119    /// lane able to start a task (a push, or a serial lane's task ending)
120    /// sets it and puts the lane in the ring if it wasn't; only a thread
121    /// that finds the lane unable to start one clears it, as it takes the
122    /// lane from the ring.
123    in_ring: bool,
124}
125
126impl Pool {
127    /// A pool of up to `threads` worker threads, which start as tasks
128    /// arrive.
129    #[cfg(not(target_family = "wasm"))]
130    #[must_use]
131    pub fn new(threads: usize) -> Pool {
132        Pool { workers: Arc::new(Workers { shared: Arc::new(Shared::new(threads)) }) }
133    }
134
135    /// A pool without threads, whose tasks run when [`run_until`](Self::run_until)
136    /// runs them, on one thread.
137    #[must_use]
138    pub fn local() -> Pool {
139        Pool { workers: Arc::new(Workers { shared: Arc::new(Shared::new(0)) }) }
140    }
141
142    /// The most worker threads the pool runs: none for a
143    /// [`local`](Self::local) pool.
144    #[must_use]
145    pub(crate) fn threads(&self) -> usize {
146        self.workers.shared.max_threads
147    }
148
149    /// Runs `task` on the pool, in its own lane.
150    pub fn spawn(&self, task: impl FnOnce() + Send + 'static) {
151        self.workers.shared.push(&self.workers.shared.lane, Box::new(task));
152    }
153
154    /// Stops the pool now, whatever clones and groups of it are left, as when
155    /// the last of them drops: its workers end once their current tasks
156    /// return, the tasks waiting for a worker drop, and tasks spawned later
157    /// drop at once. For an owner whose work may still be held where it
158    /// can't drop, such as a renderer forgotten with its graphics.
159    pub fn shut_down(&self) {
160        self.workers.shared.stop();
161    }
162
163    /// Calls `waker`, from the spawning thread, whenever a task arrives
164    /// while none were queued, so that the host of a local pool knows to
165    /// run it.
166    pub fn set_waker(&self, waker: Option<Waker>) {
167        *self.workers.shared.waker.lock() = waker;
168    }
169
170    /// Calls `handler` with the message of each task that panics, after the
171    /// panic hook reported it. The task ends as any other, and the pool goes
172    /// on, so the owner of what the task worked on fails it.
173    pub fn set_panic_handler(&self, handler: Option<PanicHandler>) {
174        *self.workers.shared.panic_handler.lock() = handler;
175    }
176
177    /// Runs queued tasks on this thread, one from each lane in turn, until
178    /// none are left or `stop` returns true (asked after each task), as a
179    /// host whose time slice is over does. Returns whether tasks remain.
180    #[must_use = "tasks may remain once `stop` stopped the run"]
181    pub fn run_until(&self, mut stop: impl FnMut() -> bool) -> bool {
182        let shared = &self.workers.shared;
183        loop {
184            let next = shared.next(&mut shared.ring.lock());
185            let Some((lane, task)) = next else { return false };
186            shared.run(&lane, task);
187            if stop() {
188                return !shared.ring.lock().lanes.is_empty();
189            }
190        }
191    }
192
193    /// Runs queued tasks on this thread until none are left, including
194    /// those they spawn.
195    pub fn run_all(&self) {
196        let _ = self.run_until(|| false);
197    }
198
199    /// Whether this thread is one of the pool's workers.
200    fn is_worker(&self) -> bool {
201        self.workers.shared.threads.lock().ids.contains(&std::thread::current().id())
202    }
203}
204
205impl std::fmt::Debug for Pool {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("Pool").field("threads", &self.threads()).finish_non_exhaustive()
208    }
209}
210
211impl TaskGroup {
212    /// A new lane of `pool`.
213    #[must_use]
214    pub fn new(pool: &Pool) -> TaskGroup {
215        TaskGroup { pool: pool.clone(), lane: Arc::default() }
216    }
217
218    /// A new lane of `pool` that runs at most one of its tasks at a time, in
219    /// the order they were spawned, on whichever thread takes each. A task
220    /// that one of its tasks spawns into the group runs after that task.
221    #[must_use]
222    pub fn serial(pool: &Pool) -> TaskGroup {
223        let lane = Lane { state: Mutex::new(LaneState { serial: true, ..LaneState::default() }), ..Lane::default() };
224        TaskGroup { pool: pool.clone(), lane: Arc::new(lane) }
225    }
226
227    /// The pool the group's tasks run on.
228    #[must_use]
229    pub(crate) fn pool(&self) -> &Pool {
230        &self.pool
231    }
232
233    /// Runs `task` on the pool, in the group's lane.
234    pub fn spawn(&self, task: impl FnOnce() + Send + 'static) {
235        self.pool.workers.shared.push(&self.lane, Box::new(task));
236    }
237
238    /// Returns once none of the group's tasks are queued or running,
239    /// including those they spawn into the group meanwhile. It runs the
240    /// queued ones on this thread, where a task that panics counts as ended
241    /// as it does on a worker, then waits for those that run on the pool's
242    /// workers. A [`serial`](Self::serial) group's next task runs here only
243    /// once none of its tasks runs elsewhere. On a [`local`](Pool::local)
244    /// pool it doesn't wait: a task that runs there runs on this thread,
245    /// below this call, so a serial group's tasks queued behind it stay
246    /// queued.
247    ///
248    /// # Panics
249    ///
250    /// On one of the pool's workers, which a running task could be waiting
251    /// for.
252    pub(crate) fn wait(&self) {
253        assert!(!self.pool.is_worker(), "a task group was waited on from a task of its pool");
254        let shared = &self.pool.workers.shared;
255        let waits = self.pool.threads() > 0;
256        let lane = &self.lane;
257        let mut state = lane.state.lock();
258        loop {
259            if shared.is_stopped() {
260                // A stopped pool starts no task: those queued drop.
261                let dropped = std::mem::take(&mut state.tasks);
262                drop(state);
263                drop(dropped);
264                state = lane.state.lock();
265                if state.running == 0 || !waits {
266                    return;
267                }
268                lane.ended.wait(&mut state);
269            } else if let Some(task) = state.start() {
270                drop(state);
271                shared.run(lane, task);
272                state = lane.state.lock();
273            } else if state.running == 0 || !waits {
274                return;
275            } else {
276                lane.ended.wait(&mut state);
277            }
278        }
279    }
280}
281
282impl std::fmt::Debug for TaskGroup {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.debug_struct("TaskGroup").field("pool", &self.pool).finish_non_exhaustive()
285    }
286}
287
288impl Shared {
289    fn new(max_threads: usize) -> Shared {
290        Shared {
291            ring: Mutex::default(),
292            work: Condvar::new(),
293            lane: Arc::default(),
294            waker: Mutex::new(None),
295            panic_handler: Mutex::new(None),
296            max_threads,
297            threads: Mutex::default(),
298            stopped: AtomicBool::new(false),
299        }
300    }
301
302    fn push(self: &Arc<Self>, lane: &Arc<Lane>, task: Task) {
303        if self.is_stopped() {
304            return;
305        }
306        let (joins, startable) = {
307            let mut state = lane.state.lock();
308            state.tasks.push_back(task);
309            let joins = state.join();
310            // A serial lane's task that doesn't join the ring waits for the
311            // lane's other tasks, not for a worker.
312            (joins, joins || !state.serial)
313        };
314        let (was_idle, start) = {
315            let mut ring = self.ring.lock();
316            let was_idle = joins && self.enter(&mut ring, lane);
317            // Every worker is busy: another starts, if the pool may run one.
318            let start = startable && ring.idle == 0 && !self.is_stopped() && ring.started < self.max_threads;
319            ring.started += usize::from(start);
320            (was_idle, start)
321        };
322        if start {
323            self.start_worker();
324        }
325        if was_idle {
326            self.wake();
327        }
328    }
329
330    /// Puts `lane`, which [`LaneState::join`] marked, at the back of the
331    /// ring, and returns whether the ring was empty.
332    fn enter(&self, ring: &mut Ring, lane: &Arc<Lane>) -> bool {
333        let was_empty = ring.lanes.is_empty();
334        ring.lanes.push_back(Arc::clone(lane));
335        self.work.notify_one();
336        was_empty
337    }
338
339    /// Calls the waker, if the pool has one.
340    fn wake(&self) {
341        let waker = self.waker.lock().clone();
342        if let Some(waker) = waker {
343            waker();
344        }
345    }
346
347    /// Takes the next task, from the first lane in the ring that may start
348    /// one, which goes to the back if it may start another. The lanes before
349    /// it, which may not, leave the ring. Its lane counts it running.
350    fn next(&self, ring: &mut Ring) -> Option<(Arc<Lane>, Task)> {
351        if self.is_stopped() {
352            return None;
353        }
354        while let Some(lane) = ring.lanes.pop_front() {
355            let mut state = lane.state.lock();
356            let Some(task) = state.start() else {
357                state.in_ring = false;
358                continue;
359            };
360            if state.may_start() {
361                ring.lanes.push_back(Arc::clone(&lane));
362                // Another worker takes the lane's next task.
363                self.work.notify_one();
364            } else {
365                state.in_ring = false;
366            }
367            drop(state);
368            return Some((lane, task));
369        }
370        None
371    }
372
373    /// Runs `task`, which `lane` counts running, and counts it ended once it
374    /// and its captures are gone, even if it panics: the panic goes to the
375    /// pool's panic handler instead of up this thread. A serial lane with tasks
376    /// queued goes back in the ring then. No worker starts for it: the
377    /// thread that ran the task goes on to take tasks, a worker's or
378    /// [`Pool::run_until`]'s from the ring, a [`TaskGroup::wait`]'s from
379    /// the lane.
380    fn run(&self, lane: &Arc<Lane>, task: Task) {
381        struct Ended<'a>(&'a Shared, &'a Arc<Lane>);
382        impl Drop for Ended<'_> {
383            fn drop(&mut self) {
384                let Ended(shared, lane) = *self;
385                let (joins, dropped) = {
386                    let mut state = lane.state.lock();
387                    state.running -= 1;
388                    // On a stopped pool, the tasks a serial lane held back
389                    // behind this one drop rather than start.
390                    let dropped = if shared.is_stopped() { std::mem::take(&mut state.tasks) } else { VecDeque::new() };
391                    (state.join(), dropped)
392                };
393                lane.ended.notify_all();
394                drop(dropped);
395                if joins {
396                    // The ring's lock is released before the waker, which may
397                    // spawn.
398                    let was_empty = shared.enter(&mut shared.ring.lock(), lane);
399                    if was_empty {
400                        shared.wake();
401                    }
402                }
403            }
404        }
405        let _ended = Ended(self, lane);
406        if let Err(message) = crate::exec::panic::catch(task) {
407            let handler = self.panic_handler.lock().clone();
408            if let Some(handler) = handler {
409                handler(message);
410            }
411        }
412    }
413
414    /// Whether the pool stopped.
415    fn is_stopped(&self) -> bool {
416        self.stopped.load(Ordering::SeqCst)
417    }
418
419    /// Stops the workers once their tasks return, and waits for them unless
420    /// this runs on a library thread (`thread::Joined`), such as one of them.
421    /// The tasks waiting in the ring drop, and those spawned later drop at
422    /// once.
423    fn stop(&self) {
424        {
425            let _ring = self.ring.lock();
426            self.stopped.store(true, Ordering::SeqCst);
427        }
428        self.work.notify_all();
429        // Joined outside the lock, which a task that spawns takes.
430        let threads = std::mem::take(&mut *self.threads.lock());
431        drop(threads);
432        // The tasks left, dropped here rather than with the last worker.
433        let lanes = std::mem::take(&mut self.ring.lock().lanes);
434        let tasks: Vec<VecDeque<Task>> =
435            lanes.iter().map(|lane| std::mem::take(&mut lane.state.lock().tasks)).collect();
436        drop(tasks);
437    }
438
439    /// Starts the worker that `push` counted started.
440    #[cfg_attr(target_family = "wasm", expect(clippy::unused_self, reason = "the browser's pools start no threads"))]
441    fn start_worker(self: &Arc<Self>) {
442        #[cfg(not(target_family = "wasm"))]
443        {
444            let mut threads = self.threads.lock();
445            let shared = Arc::clone(self);
446            match crate::exec::thread::spawn(format!("Worker {}", threads.ids.len() + 1), move || shared.work()) {
447                Ok(thread) => {
448                    threads.ids.push(thread.thread().id());
449                    threads.joined.push(Joined::new(thread));
450                }
451                // The running workers take the tasks; without any, they
452                // wait for a later task to start one.
453                Err(error) => {
454                    self.ring.lock().started -= 1;
455                    tracing::error!(target: crate::log_target::GENERAL, error = %error, "Can't start a pool worker");
456                }
457            }
458        }
459    }
460
461    /// A worker's loop, until the pool stops.
462    #[cfg(not(target_family = "wasm"))]
463    fn work(&self) {
464        loop {
465            let next = {
466                let mut ring = self.ring.lock();
467                loop {
468                    if self.is_stopped() {
469                        return;
470                    }
471                    if let Some(next) = self.next(&mut ring) {
472                        break next;
473                    }
474                    ring.idle += 1;
475                    self.work.wait(&mut ring);
476                    ring.idle -= 1;
477                }
478            };
479            let (lane, task) = next;
480            self.run(&lane, task);
481        }
482    }
483}
484
485impl LaneState {
486    /// Whether the lane has a task queued that it may start now: any, or for
487    /// a serial lane, one while none of its tasks runs.
488    fn may_start(&self) -> bool {
489        !self.tasks.is_empty() && (!self.serial || self.running == 0)
490    }
491
492    /// Takes the next task, which the lane counts running, if it may start
493    /// one.
494    fn start(&mut self) -> Option<Task> {
495        if !self.may_start() {
496            return None;
497        }
498        self.running += 1;
499        self.tasks.pop_front()
500    }
501
502    /// Marks the lane in the ring if it may start a task and isn't marked.
503    /// Returns whether it did: the caller then puts it there with
504    /// [`Shared::enter`].
505    fn join(&mut self) -> bool {
506        let joins = !self.in_ring && self.may_start();
507        self.in_ring |= joins;
508        joins
509    }
510}
511
512impl Drop for Workers {
513    fn drop(&mut self) {
514        self.shared.stop();
515    }
516}
517
518#[cfg(test)]
519mod tests {
520    use std::sync::atomic::AtomicUsize;
521    use std::sync::mpsc;
522
523    use super::*;
524
525    #[test]
526    fn a_group_waits_for_its_tasks_on_the_workers() {
527        let pool = Pool::new(4);
528        let group = TaskGroup::new(&pool);
529        let gate = Arc::new((Mutex::new(false), Condvar::new()));
530        let (running, run) = mpsc::channel();
531        let ended = Arc::new(AtomicUsize::new(0));
532        for _ in 0..8 {
533            let (gate, running, ended) = (Arc::clone(&gate), running.clone(), Arc::clone(&ended));
534            group.spawn(move || {
535                running.send(()).unwrap();
536                let (open, opened) = &*gate;
537                let mut open = open.lock();
538                while !*open {
539                    opened.wait(&mut open);
540                }
541                ended.fetch_add(1, Ordering::SeqCst);
542            });
543        }
544        // Every worker runs a task, and four more wait in the queue, for the
545        // workers or for the waiting thread.
546        for _ in 0..4 {
547            run.recv().unwrap();
548        }
549        // The gate opens while the wait waits, or before it begins: either
550        // way, the wait returns after every task ends.
551        let opener = Arc::clone(&gate);
552        std::thread::spawn(move || {
553            *opener.0.lock() = true;
554            opener.1.notify_all();
555        });
556        group.wait();
557        assert_eq!(ended.load(Ordering::SeqCst), 8);
558    }
559
560    #[test]
561    fn workers_start_as_tasks_arrive_up_to_the_limit() {
562        let pool = Pool::new(3);
563        let started = || pool.workers.shared.threads.lock().ids.len();
564        assert_eq!(started(), 0);
565        let group = TaskGroup::new(&pool);
566        let gate = Arc::new((Mutex::new(false), Condvar::new()));
567        let (running, run) = mpsc::channel();
568        for _ in 0..5 {
569            let (gate, running) = (Arc::clone(&gate), running.clone());
570            group.spawn(move || {
571                running.send(()).unwrap();
572                let (open, opened) = &*gate;
573                let mut open = open.lock();
574                while !*open {
575                    opened.wait(&mut open);
576                }
577            });
578        }
579        for _ in 0..3 {
580            run.recv().unwrap();
581        }
582        assert_eq!(started(), 3);
583        *gate.0.lock() = true;
584        gate.1.notify_all();
585        group.wait();
586        assert_eq!(started(), 3);
587    }
588
589    #[test]
590    fn a_group_waits_for_the_tasks_its_tasks_spawn() {
591        let pool = Pool::new(2);
592        let group = TaskGroup::new(&pool);
593        let count = Arc::new(AtomicUsize::new(0));
594        let (inner, counter) = (group.clone(), Arc::clone(&count));
595        group.spawn(move || {
596            inner.spawn(move || {
597                counter.fetch_add(1, Ordering::SeqCst);
598            });
599        });
600        group.wait();
601        assert_eq!(count.load(Ordering::SeqCst), 1);
602    }
603
604    #[test]
605    fn a_wait_runs_queued_tasks_on_the_waiting_thread() {
606        let pool = Pool::new(1);
607        let group = TaskGroup::new(&pool);
608        let (blocked, block) = mpsc::channel::<()>();
609        let (started, start) = mpsc::channel::<()>();
610        // Holds the one worker.
611        pool.spawn(move || {
612            started.send(()).unwrap();
613            let _ = block.recv();
614        });
615        start.recv().unwrap();
616        let ran_on = Arc::new(Mutex::new(None));
617        let on = Arc::clone(&ran_on);
618        group.spawn(move || *on.lock() = Some(std::thread::current().id()));
619        group.wait();
620        assert_eq!(*ran_on.lock(), Some(std::thread::current().id()));
621        drop(blocked);
622    }
623
624    #[test]
625    fn workers_visit_the_lanes_in_turn() {
626        let pool = Pool::local();
627        let (busy, other) = (TaskGroup::new(&pool), TaskGroup::new(&pool));
628        let order = Arc::new(Mutex::new(Vec::new()));
629        for value in 0..3 {
630            let order = Arc::clone(&order);
631            busy.spawn(move || order.lock().push(value));
632        }
633        let o = Arc::clone(&order);
634        other.spawn(move || o.lock().push(10));
635        pool.run_all();
636        assert_eq!(*order.lock(), vec![0, 10, 1, 2]);
637    }
638
639    #[test]
640    fn a_local_pool_runs_when_its_host_runs_it() {
641        let pool = Pool::local();
642        let wakes = Arc::new(AtomicUsize::new(0));
643        let w = Arc::clone(&wakes);
644        pool.set_waker(Some(Arc::new(move || {
645            w.fetch_add(1, Ordering::SeqCst);
646        })));
647        let count = Arc::new(AtomicUsize::new(0));
648        for _ in 0..3 {
649            let count = Arc::clone(&count);
650            pool.spawn(move || {
651                count.fetch_add(1, Ordering::SeqCst);
652            });
653        }
654        assert_eq!(wakes.load(Ordering::SeqCst), 1);
655        assert_eq!(count.load(Ordering::SeqCst), 0);
656        // A run that stops after each task runs one.
657        assert!(pool.run_until(|| true));
658        assert_eq!(count.load(Ordering::SeqCst), 1);
659        assert!(!pool.run_until(|| false));
660        assert_eq!(count.load(Ordering::SeqCst), 3);
661        pool.spawn(|| {});
662        assert_eq!(wakes.load(Ordering::SeqCst), 2);
663    }
664
665    #[test]
666    fn a_wait_on_a_local_pool_runs_the_group_and_returns() {
667        let pool = Pool::local();
668        let group = TaskGroup::new(&pool);
669        let order = Arc::new(Mutex::new(Vec::new()));
670        let (inner, o) = (group.clone(), Arc::clone(&order));
671        group.spawn(move || {
672            o.lock().push(1);
673            // From a task of its own: it can't wait for itself.
674            inner.wait();
675            o.lock().push(3);
676        });
677        let o = Arc::clone(&order);
678        group.spawn(move || o.lock().push(2));
679        let o = Arc::clone(&order);
680        pool.spawn(move || o.lock().push(4));
681        group.wait();
682        assert_eq!(*order.lock(), vec![1, 2, 3]);
683        pool.run_all();
684        assert_eq!(*order.lock(), vec![1, 2, 3, 4]);
685    }
686
687    #[test]
688    fn a_task_that_panics_still_ends() {
689        let pool = Pool::new(1);
690        let group = TaskGroup::new(&pool);
691        group.spawn(|| panic!("a task panicked"));
692        let (done, finished) = mpsc::channel();
693        group.spawn(move || done.send(()).unwrap());
694        finished.recv().unwrap();
695        group.wait();
696    }
697
698    #[test]
699    fn a_task_that_panics_tells_the_panic_handler() {
700        let pool = Pool::new(1);
701        let (report, reported) = mpsc::channel();
702        pool.set_panic_handler(Some(Arc::new(move |message| report.send(message).unwrap())));
703        pool.spawn(|| panic!("a task panicked"));
704        assert_eq!(reported.recv().unwrap(), "a task panicked");
705    }
706
707    #[test]
708    fn a_wait_that_runs_a_task_that_panics_returns() {
709        let pool = Pool::local();
710        let group = TaskGroup::new(&pool);
711        let ran = Arc::new(AtomicUsize::new(0));
712        group.spawn(|| panic!("a task panicked"));
713        let r = Arc::clone(&ran);
714        group.spawn(move || {
715            r.fetch_add(1, Ordering::SeqCst);
716        });
717        group.spawn(|| panic!("another task panicked"));
718        group.wait();
719        assert_eq!(ran.load(Ordering::SeqCst), 1);
720        assert!(!pool.run_until(|| false));
721    }
722
723    /// The last owner of a pool may be one of its own tasks.
724    #[test]
725    fn a_pool_dropped_by_its_own_task_stops() {
726        let pool = Arc::new(Mutex::new(Some(Pool::new(2))));
727        let (done, dropped) = mpsc::channel();
728        let owner = Arc::clone(&pool);
729        let spawner = pool.lock().clone().unwrap();
730        drop(pool);
731        spawner.spawn(move || {
732            drop(owner.lock().take());
733            done.send(()).unwrap();
734        });
735        drop(spawner);
736        dropped.recv().unwrap();
737    }
738
739    #[test]
740    fn a_serial_group_runs_its_tasks_one_at_a_time_in_order() {
741        let pool = Pool::new(4);
742        let group = TaskGroup::serial(&pool);
743        let (active, overlapped) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
744        let order = Arc::new(Mutex::new(Vec::new()));
745        let (gate, open) = mpsc::channel::<()>();
746        let (started, start) = mpsc::channel();
747        group.spawn(move || {
748            started.send(()).unwrap();
749            let _ = open.recv();
750        });
751        start.recv().unwrap();
752        for value in 0..40 {
753            let (active, overlapped, order) = (Arc::clone(&active), Arc::clone(&overlapped), Arc::clone(&order));
754            group.spawn(move || {
755                if active.fetch_add(1, Ordering::SeqCst) > 0 {
756                    overlapped.fetch_add(1, Ordering::SeqCst);
757                }
758                order.lock().push(value);
759                active.fetch_sub(1, Ordering::SeqCst);
760                // It ends as any other: the next task still runs.
761                assert!(value != 20, "a task panicked");
762            });
763        }
764        // While a task runs, the lane, which can't start another, is out of
765        // the ring, and the queued tasks start no workers.
766        assert!(pool.workers.shared.ring.lock().lanes.is_empty());
767        assert_eq!(pool.workers.shared.threads.lock().ids.len(), 1);
768        drop(gate);
769        let (done, finished) = mpsc::channel();
770        group.spawn(move || done.send(()).unwrap());
771        finished.recv().unwrap();
772        assert_eq!(*order.lock(), (0..40).collect::<Vec<_>>());
773        assert_eq!(overlapped.load(Ordering::SeqCst), 0);
774    }
775
776    #[test]
777    fn a_serial_task_spawns_into_its_group_behind_itself() {
778        let pool = Pool::new(4);
779        let group = TaskGroup::serial(&pool);
780        let order = Arc::new(Mutex::new(Vec::new()));
781        let (inner, o) = (group.clone(), Arc::clone(&order));
782        group.spawn(move || {
783            let o2 = Arc::clone(&o);
784            inner.spawn(move || o2.lock().push(2));
785            o.lock().push(1);
786        });
787        group.wait();
788        assert_eq!(*order.lock(), vec![1, 2]);
789    }
790
791    #[test]
792    fn a_wait_on_a_serial_group_runs_nothing_while_one_of_its_tasks_runs() {
793        let pool = Pool::new(1);
794        let group = TaskGroup::serial(&pool);
795        let ended = Arc::new(AtomicUsize::new(0));
796        let (started, start) = mpsc::channel();
797        let (release, released) = mpsc::channel::<()>();
798        let e = Arc::clone(&ended);
799        group.spawn(move || {
800            started.send(()).unwrap();
801            let _ = released.recv();
802            e.fetch_add(1, Ordering::SeqCst);
803        });
804        start.recv().unwrap();
805        let saw = Arc::new(Mutex::new(Vec::new()));
806        for _ in 0..3 {
807            let (e, saw) = (Arc::clone(&ended), Arc::clone(&saw));
808            group.spawn(move || {
809                let before = e.load(Ordering::SeqCst);
810                saw.lock().push(before);
811                e.fetch_add(1, Ordering::SeqCst);
812            });
813        }
814        // The first task ends while the wait waits, or before it begins.
815        std::thread::spawn(move || drop(release));
816        group.wait();
817        assert_eq!(*saw.lock(), vec![1, 2, 3]);
818    }
819
820    #[test]
821    fn a_serial_group_on_a_local_pool_runs_in_order() {
822        let pool = Pool::local();
823        let group = TaskGroup::serial(&pool);
824        let order = Arc::new(Mutex::new(Vec::new()));
825        let (inner, o) = (group.clone(), Arc::clone(&order));
826        group.spawn(move || {
827            o.lock().push(1);
828            // Its group's next task can't start while this one runs.
829            inner.wait();
830            let o2 = Arc::clone(&o);
831            inner.spawn(move || o2.lock().push(5));
832            o.lock().push(2);
833        });
834        group.spawn(|| panic!("a task panicked"));
835        for value in [3, 4] {
836            let o = Arc::clone(&order);
837            group.spawn(move || o.lock().push(value));
838        }
839        assert!(pool.run_until(|| true));
840        assert_eq!(*order.lock(), vec![1, 2]);
841        group.wait();
842        assert_eq!(*order.lock(), vec![1, 2, 3, 4, 5]);
843        assert!(!pool.run_until(|| false));
844    }
845
846    #[test]
847    fn a_pool_shut_down_while_a_clone_lives_stops_its_workers() {
848        let pool = Pool::new(2);
849        let (ran, first) = mpsc::channel();
850        pool.spawn(move || ran.send(()).unwrap());
851        first.recv().unwrap();
852        let worker = pool.workers.shared.threads.lock().joined.len();
853        assert_eq!(worker, 1);
854        // As a renderer forgotten with its graphics holds its pool.
855        std::mem::forget(pool.clone());
856        pool.shut_down();
857        assert!(pool.workers.shared.threads.lock().joined.is_empty());
858        let (later, dropped) = mpsc::channel::<()>();
859        pool.spawn(move || later.send(()).unwrap());
860        // The task drops at once, unrun.
861        assert!(dropped.recv().is_err(), "a task ran after the shutdown");
862    }
863
864    #[test]
865    fn a_shut_down_drops_the_tasks_behind_a_running_serial_task() {
866        let pool = Pool::new(1);
867        let group = TaskGroup::serial(&pool);
868        let (started, start) = mpsc::channel();
869        let (release, blocked) = mpsc::channel::<()>();
870        group.spawn(move || {
871            started.send(()).unwrap();
872            let _ = blocked.recv();
873        });
874        start.recv().unwrap();
875        let ran = Arc::new(AtomicUsize::new(0));
876        let r = Arc::clone(&ran);
877        group.spawn(move || {
878            r.fetch_add(1, Ordering::SeqCst);
879        });
880        // From a library thread, as a runtime's: it doesn't wait for the
881        // running task.
882        #[expect(clippy::redundant_clone, reason = "the test thread keeps the pool")]
883        let shut = pool.clone();
884        crate::exec::thread::spawn("shut down", move || shut.shut_down()).unwrap().join().unwrap();
885        drop(release);
886        group.wait();
887        assert_eq!(ran.load(Ordering::SeqCst), 0);
888    }
889
890    #[test]
891    fn a_wait_from_a_worker_panics() {
892        let pool = Pool::new(1);
893        let group = TaskGroup::new(&pool);
894        let (result, outcome) = mpsc::channel();
895        #[expect(clippy::redundant_clone, reason = "the test thread keeps the group")]
896        let inner = group.clone();
897        pool.spawn(move || {
898            let waited = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| inner.wait()));
899            result.send(waited.is_err()).unwrap();
900        });
901        assert!(outcome.recv().unwrap());
902    }
903}