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