bottle 0.1.0

Actor model framework for Rust.
use std::thread;
use std::sync::{Arc};
use crate::{Thread, Remote};
use std::mem;
use std::cell::UnsafeCell;

pub trait Scheduler : Send + Sync {
	//fn handle<T>(&'static self, t: T) -> Remote<T>;
	fn next_thread(&self) -> &Arc<Thread>;
}

pub struct SimpleScheduler {
	threads: Vec<Arc<Thread>>
}

impl SimpleScheduler {
	pub fn new(thread_count: usize) -> SimpleScheduler {
		let mut threads = Vec::with_capacity(thread_count);
		for _ in 0..thread_count {
			threads.push(Thread::new())
		}

		SimpleScheduler {
			threads: threads
		}
	}

	fn min_thread(&self) -> &Arc<Thread> {
		let mut min_thread = &self.threads[0];
		let mut min = min_thread.len();
		let mut min_count = min_thread.count();

		for i in 1..self.threads.len() {
			let thread = &self.threads[i];
			let len = thread.len();

			if len <= min {
				let count = thread.count();
				if len < min || count < min_count {
					min_thread = thread;
					min = len;
					min_count = count;
				}
			}
		}

		return min_thread
	}

	pub fn handle<T: 'static + Send>(&self, t: T) -> Remote<T> {
		Remote::new(self.next_thread(), t)
	}

	/// Start the scheduler. Does not block.
	/// Return the join handle of every thread.
	/// If you want to block until all the threads are terminated,
	/// use `JoinHandle`.`join` on the returned handles.
	pub fn start(&self) -> Vec<thread::JoinHandle<()>> {
		let mut children = Vec::with_capacity(self.threads.len());

		for t in self.threads.iter() {
			let arc = t.clone();
			children.push(thread::spawn(move || {
				Thread::start(&arc)
			}));
		}

		children
	}
}

impl Scheduler for SimpleScheduler {
	fn next_thread(&self) -> &Arc<Thread> {
		self.min_thread()
	}
}