Skip to content

Instantly share code, notes, and snippets.

@randomPoison
Forked from anonymous/playground.rs
Last active August 15, 2017 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randomPoison/0b9b5fa516fb507479b536815073b9d0 to your computer and use it in GitHub Desktop.
Save randomPoison/0b9b5fa516fb507479b536815073b9d0 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;
#[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<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() {
let count = Arc::new(RwLock::new(MyCount::new()));
let count_clone = count.clone();
thread::spawn(move || {
// 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_clone).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