Skip to content

Instantly share code, notes, and snippets.

Created August 15, 2017 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/e02cbd95713506b2f07164c3f13ecc0f to your computer and use it in GitHub Desktop.
Save anonymous/e02cbd95713506b2f07164c3f13ecc0f to your computer and use it in GitHub Desktop.
Rust code shared from the playground
#![feature(plugin)]
#![plugin(rocket_codegen)]
use std::sync::RwLock;
use std::sync::Arc;
use std::time;
use std::thread;
extern crate rocket;
use rocket::State;
#[macro_use] extern crate lazy_static;
lazy_static! {
// Maybe don't need Arc and RwLock here.
static ref COUNT: Arc<RwLock<MyCount>> = {
Arc::new(RwLock::new(MyCount::new()))
};
}
#[derive(Debug)]
struct MyCount {
count: i32
}
impl MyCount {
fn new() -> MyCount { MyCount { count: 10 } }
fn reset (&mut self) { self.count = 0; }
}
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[get("/count")]
fn add(hit_count: State<RwLock<MyCount>>) -> String {
let old_count = hit_count.read().unwrap().count;
hit_count.write().unwrap().count = old_count + 1;
format!("Changing count from {} -> to {}", old_count, hit_count.read().unwrap().count)
}
fn main() {
thread::spawn( || {
// The first line that is commented out, compiles, however i only want
// there be a single instance of MyCount which Rocket can manage,
// and it can be read/altered in another thread.
//rocket::ignite().manage(RwLock::new(MyCount::new())).mount("/", routes![index,add]).launch();
rocket::ignite().manage(*COUNT).mount("/", routes![index,add]).launch();
});
let sleep_duration = time::Duration::from_millis(1000);
loop {
thread::sleep(sleep_duration);
println!("sleep ... count: {:?}", *COUNT.read().unwrap());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment