Rust TaskScheduler Stuff
ActivePublic

Authored by bcs on Sep 25 2016, 11:59 PM.
extern crate hyper;
extern crate yup_oauth2 as oauth2;
extern crate google_drive3 as drive3;
use std::thread;
use std::sync::mpsc::{sync_channel, channel, Iter, Receiver, SyncSender};
use std::result;
use std::error;
use std::boxed::Box;
use std::marker::Send;
use std::marker::PhantomData;
type TaskError = String;
type Result<T> = result::Result<T, TaskError>;
pub struct Task<F : Send> {
task_fn: F,
}
impl<R : Send, F : Send> Task<F> where F: FnOnce() -> Result<R> {
fn new(f: F) -> Task<F> {
Task { task_fn: f }
}
fn run(self) -> Result<R> {
(self.task_fn)()
}
}
fn new_worker<R : Send, F : Send>(ch: Receiver<Task<F>>, results_ch: SyncSender<Result<R>>)
-> thread::JoinHandle<()> where F: FnOnce() -> Result<R> {
thread::spawn(move || {
for task in ch.into_iter() {
results_ch.send(task.run());
}
})
}
pub struct TaskScheduler<R : Send, F : Send> {
workers : Vec<(SyncSender<Task<F>>, thread::JoinHandle<()>)>,
result_queue : Receiver<Result<R>>
}
impl<R : Send, F : Send> TaskScheduler<R, F> where F: FnOnce() -> Result<R> {
pub fn new(worker_count: i32) -> TaskScheduler<R, F> {
let workers : Vec<(SyncSender<Task<F>>, thread::JoinHandle<()>)> = vec!();
let (results_ch, result_queue) = sync_channel(1000);
for i in 0..worker_count {
let (worker_ch, worker_queue) = sync_channel(1000);
workers.push(
(worker_ch, new_worker(worker_queue, results_ch.clone()))
);
}
TaskScheduler {
workers: workers,
result_queue: result_queue,
}
}
pub fn iter(&self) -> Iter<Result<R>> {
self.result_queue.iter()
}
}
bcs created this paste.Sep 25 2016, 11:59 PM