mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! What the orchestrator drops on its workers, and that it waits for them.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;

use super::orchestrator;
use crate::exec::pool::Pool;

/// Calls its function as it drops.
struct OnDrop<F: FnOnce()>(Option<F>);

impl<F: FnOnce()> Drop for OnDrop<F> {
    fn drop(&mut self) {
        if let Some(f) = self.0.take() {
            f();
        }
    }
}

#[test]
fn a_value_dropped_on_the_workers_drops_on_a_worker() {
    let orchestrator = orchestrator(&crate::tests::pool());
    let (sender, dropped_on) = mpsc::channel();
    orchestrator.drop_on_workers(OnDrop(Some(move || sender.send(thread::current().id()).unwrap())));
    assert_ne!(dropped_on.recv().unwrap(), thread::current().id());
}

/// The drop waits for a value that a worker drops, and drops one that no
/// worker took yet itself.
#[test]
fn the_orchestrator_waits_for_what_it_drops_on_workers() {
    let orchestrator = orchestrator(&Pool::new(1));
    // The pool's one worker drops the first value, which waits for the
    // second to drop.
    let (started, worker_started) = mpsc::channel();
    let (open, gate) = mpsc::channel();
    let worker_done = Arc::new(AtomicBool::new(false));
    let done = Arc::clone(&worker_done);
    orchestrator.drop_on_workers(OnDrop(Some(move || {
        started.send(()).unwrap();
        gate.recv().unwrap();
        done.store(true, Ordering::SeqCst);
    })));
    worker_started.recv().unwrap();
    let (sender, queued_dropped_on) = mpsc::channel();
    orchestrator.drop_on_workers(OnDrop(Some(move || {
        sender.send(thread::current().id()).unwrap();
        open.send(()).unwrap();
    })));

    drop(orchestrator);
    assert_eq!(queued_dropped_on.recv().unwrap(), thread::current().id(), "the drop dropped the queued value");
    assert!(worker_done.load(Ordering::SeqCst), "the drop waited for the worker's");
}