Created
February 23, 2024 19:25
-
-
Save fancellu/42596073a211a0d6cc325d6b9149143e to your computer and use it in GitHub Desktop.
Rust example of Tokio Mutex usage between threads
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
use std::sync::Arc; | |
use tokio::sync::Mutex; | |
// async tokio function to increment i32 behind arc mutex | |
async fn increment(remote: Arc<Mutex<i32>>) { | |
println!("trying to lock"); | |
let mut tvc = remote.lock().await; | |
println!("incremented"); | |
*tvc += 1; | |
} | |
#[tokio::main] | |
async fn main() { | |
let tv_channel = 10; | |
let remote = Mutex::new(tv_channel); | |
let remote_arc = Arc::new(remote); | |
// add 5 to it ourselves | |
let mut tvc = remote_arc.lock().await; | |
*tvc += 5; | |
println!("{}", *tvc); | |
assert_eq!(*tvc, 15); | |
// If I don't drop, increment won't be able to lock! | |
drop(tvc); | |
println!("About to spawn increment, twice"); | |
let handle1 = tokio::spawn(increment(remote_arc.clone())); | |
let handle2 = tokio::spawn(increment(remote_arc.clone())); | |
// I don't care about either of the return values of increment() | |
let _ = (handle1.await, handle2.await); | |
let tvc = remote_arc.lock().await; | |
println!("{}", *tvc); | |
assert_eq!(*tvc, 17); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
15
About to spawn increment, twice
trying to lock
incremented
trying to lock
incremented
17