Created
July 16, 2018 19:58
-
-
Save rust-play/b0cf083bfe4a77833c6743bc5f349c7b to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Author: Gabriel Hayes | |
// Rust Worker-Runloop Implementation | |
use std::cell::RefCell; | |
use std::rc::Rc; | |
use std::time::Duration; | |
use std::thread; | |
struct Worker { | |
job: Rc<RefCell<FnMut(i64)>>, | |
} | |
impl Worker { | |
fn new() -> Worker { | |
Worker { | |
job: Rc::new(RefCell::new(|_|{})) | |
} | |
} | |
fn contract<F: FnMut(i64) + 'static>(job: F) -> Worker { | |
Worker { | |
job: Rc::new(RefCell::new(job)) | |
} | |
} | |
fn work(&mut self, data: i64) { | |
let mut closure = self.job.borrow_mut(); | |
(&mut *closure) (data); | |
} | |
} | |
struct Runloop { | |
workers: Vec<Rc<RefCell<Worker>>>, | |
step: i64 | |
} | |
impl Runloop { | |
fn new() -> Runloop { | |
Runloop { | |
workers: Vec::new(), | |
step: 0 | |
} | |
} | |
fn add_worker(&mut self, worker: Worker) { | |
let cell = Rc::new(RefCell::new(worker)); | |
self.workers.push(cell); | |
} | |
fn run(&mut self, limit: i64) { | |
loop { | |
self.step += 1; | |
if self.step > limit { | |
return; | |
} | |
for worker_cell in self.workers.iter() { | |
let worker = worker_cell.clone(); | |
let worker = &mut *worker.borrow_mut(); | |
worker.work(self.step); | |
} | |
thread::sleep(Duration::from_millis(250)); | |
} | |
// Runloop::run(self, limit); | |
} | |
} | |
fn main() { | |
let workers = vec![ | |
Worker::contract(|a| println!("a = {}", a)), | |
Worker::contract(|b| println!("b = {}", b)), | |
Worker::contract(|c| println!("c = {}", c)), | |
Worker::contract(|d| println!("d = {}", d)), | |
Worker::contract(|e| println!("e = {}", e)), | |
Worker::contract(|f| println!("f = {}", f)) | |
]; | |
let mut runloop = Runloop::new(); | |
for worker in workers { | |
runloop.add_worker(worker); | |
} | |
runloop.run(50); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment