Created
August 15, 2017 12:52
-
-
Save anonymous/e02cbd95713506b2f07164c3f13ecc0f to your computer and use it in GitHub Desktop.
Rust code shared from the 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
#![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