use std::thread::{self, Builder};
use super::{Executor, Receiver};
#[derive(Debug)]
pub struct MultiThread {
threads: usize,
}
impl MultiThread {
pub fn new(threads: usize) -> Self {
MultiThread {
threads: threads
}
}
}
impl Executor for MultiThread {
fn start(self, recv: Receiver) {
for thread in 0 .. self.threads {
spawn_thread(thread, recv.clone());
}
}
}
#[derive(Debug, Default)]
pub struct SingleThread(());
impl SingleThread {
pub fn new() -> Self {
SingleThread(())
}
}
impl Executor for SingleThread {
fn start(self, recv: Receiver) {
spawn_thread(0, recv);
}
}
struct Sentinel {
thread: usize,
recv: Receiver
}
impl Drop for Sentinel {
fn drop(&mut self) {
if thread::panicking() {
spawn_thread(self.thread, self.recv.clone());
}
}
}
fn spawn_thread(thread: usize, recv: Receiver) {
let sentinel = Sentinel {
thread: thread,
recv: recv
};
let _ = Builder::new()
.name(format!("anterofit_worker_{}", thread))
.spawn(move ||
for exec in &sentinel.recv {
exec.exec();
}
)
.expect("Failed to spawn Anterofit worker thread");
}