Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created February 23, 2024 19:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/42596073a211a0d6cc325d6b9149143e to your computer and use it in GitHub Desktop.
Save fancellu/42596073a211a0d6cc325d6b9149143e to your computer and use it in GitHub Desktop.
Rust example of Tokio Mutex usage between threads
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);
}
@fancellu
Copy link
Author

Output

15
About to spawn increment, twice
trying to lock
incremented
trying to lock
incremented
17

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment