1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//! General library for genetic algorithm implementations.

use std::sync::mpsc;
use std::thread;

use snafu::Snafu;

mod cell;
mod fitness;
mod parameters;
mod sim_result;
mod simulation;

pub use fitness::FitnessEvaluator;
pub use parameters::Parameters;
pub use sim_result::SimResult;
use simulation::Simulation;

/// Enumeration of possible errors returned by the simulation.
#[derive(Debug, Snafu)]
pub enum SimulationError {
    /// Returned when the simulation thread failed to stop.
    JoinError,
}

struct Handle {
    pub thread_handle: thread::JoinHandle<()>,
    pub stop_tx: mpsc::Sender<bool>,
}

/// Main simulation runner.
pub struct ThreadSim {
    handle: Handle,
    rx: mpsc::Receiver<SimResult>,
}

impl ThreadSim {
    /// Starts a simulation thread using the provided parameters.
    ///
    /// `start` returns a result receiver that can be used to read result snapshots.
    pub fn start<T>(params: Parameters<T>) -> ThreadSim
    where
        T: 'static + FitnessEvaluator + Send + Sync,
    {
        let (result_tx, result_rx) = mpsc::channel();
        let (stop_tx, stop_rx) = mpsc::channel();

        let sim = Simulation::new(params);
        let thread_handle =
            thread::spawn(move || ThreadSim::internal_sim_loop(sim, stop_rx, result_tx));

        ThreadSim {
            handle: Handle {
                stop_tx,
                thread_handle,
            },
            rx: result_rx,
        }
    }

    /// Returns a reference to the simulation result receiver.
    pub fn results(&self) -> &mpsc::Receiver<SimResult> {
        &self.rx
    }

    /// Stops the simulation.
    pub fn stop(self) -> Result<(), SimulationError> {
        self.handle
            .stop_tx
            .send(true)
            .map_err(|_e| SimulationError::JoinError)?;
        self.handle
            .thread_handle
            .join()
            .map_err(|_e| SimulationError::JoinError)?;
        Ok(())
    }

    fn internal_sim_loop<T: FitnessEvaluator + Send + Sync>(
        mut sim: Simulation<T>,
        stop_rx: mpsc::Receiver<bool>,
        result_tx: mpsc::Sender<SimResult>,
    ) {
        sim.run(result_tx, stop_rx)
    }
}