Created
August 13, 2023 21:24
-
-
Save MatiasVara/d958a4668cdd87fd08e033d0b998f689 to your computer and use it in GitHub Desktop.
This example shows the use of rwlock, arc and threading.
This file contains hidden or 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
// share ownership across multiple threads | |
// https://doc.rust-lang.org/book/ch16-03-shared-state.html | |
// | |
use std::thread; | |
use std::sync::{Arc,RwLock}; | |
struct User { | |
index: u32, | |
} | |
fn main() { | |
let counter = Arc::new(RwLock::new(User { | |
index : 0, | |
})); | |
let counter_cloned = counter.clone(); | |
let handle = thread::spawn(move || { | |
let num = counter_cloned.write().unwrap(); | |
// derefence the variable | |
//*num.index +=1; | |
let mut user = num; | |
user.index += 1; | |
println!("hi number {} from the spawned thread!", user.index); | |
}); | |
handle.join().unwrap(); | |
let mut user2 = counter.write().unwrap(); | |
user2.index += 1; | |
println!("Hello, world! {}", user2.index); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment