Created
July 7, 2017 10:46
Star
You must be signed in to star a gist
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
#[derive(Worker)] | |
struct StatsWorker; | |
impl StatsWorker { | |
#![command] | |
fn write(&mut self) { | |
// Write some data to redis | |
} | |
#![command] | |
fn increment_requests(&mut self, amount: u32) { | |
self.requests += amount; | |
} | |
#![message] | |
fn get_requests(&self) -> u32 { | |
self.requests | |
} | |
} | |
fn main() { | |
let worker = StatsWorker::with_name("Statistics"); | |
// Worker handler is a structure created internally by code generation | |
// It only has channel senders to original worker, it is cheap to clone | |
let worker_handler = worker.get_handle(); | |
// Spawns worker's loop on a thread | |
worker.run(); | |
for i in 0..10 { | |
let handler = worker_handler.clone(); | |
// Calling command functions in the handler doesn't invoke the real | |
// function, instead it sends a message over the channel to real worker | |
thread::spawn(|| { handler.increment_request(1) }); | |
} | |
// Semi blocking operation, two way channel messaging happens | |
let requests = worker_handler.get_requests(); | |
// Blocks until worker's internal command's buffer is empty | |
worker_handler.finish_commands(); | |
assert!(worker_handler.get_requests(), Ok(10)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment