Skip to content

Instantly share code, notes, and snippets.

@jwo
Last active February 22, 2021 15:24
Show Gist options
  • Save jwo/f15305a1108d127820cca23498ba1a18 to your computer and use it in GitHub Desktop.
Save jwo/f15305a1108d127820cca23498ba1a18 to your computer and use it in GitHub Desktop.
Simple read-write lock in Rust. main.rs uses local variables; main-static.rs uses lazy_static to create a rw lock on a static variable.
use std::sync::RwLock;
#[macro_use]
extern crate lazy_static;
lazy_static! {
static ref MODELS: RwLock<i32> = RwLock::new(0);
}
fn update_it(number: i32) {
println!("You wanted me to update to {}", number);
let mut w = MODELS.write().unwrap();
*w = number;
println!("After, it is: {}", w);
}
fn get_number() -> i32 {
let r1 = MODELS.read().unwrap();
return *r1;
}
fn main() {
print!("r1: {}", get_number());
update_it(20);
update_it(22);
print!("r2: {}", get_number());
}
use std::sync::RwLock;
fn update_it(lock: &RwLock<i32>, number: i32) {
println!("You wanted me to update to {}", number);
let mut w = lock.write().unwrap();
*w = number;
println!("After, it is: {}", w);
}
fn get_number(lock: &RwLock<i32>) -> i32 {
let r1 = lock.read().unwrap();
return *r1;
}
fn main() {
let lock = RwLock::new(5);
print!("r1: {}", get_number(&lock));
update_it(&lock, 20);
update_it(&lock, 22);
print!("r2: {}", get_number(&lock));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment