Skip to content

Instantly share code, notes, and snippets.

@umurgdk
Created July 7, 2017 10:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save umurgdk/67445aad930fce681e8e043f8909187c to your computer and use it in GitHub Desktop.
#[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