Created
February 27, 2024 11:36
-
-
Save fancellu/dbb6f80565676b93da64a179cf00654c to your computer and use it in GitHub Desktop.
Rust tokio demo of RwLock
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
use std::sync::Arc; | |
use tokio::sync::RwLock; | |
use tokio::time::sleep; | |
use tokio::time::Duration; | |
// Demonstrates RwLock with a shared resourced | |
async fn use_read_lock(id: i32, lock: Arc<RwLock<String>>) { | |
let lock = lock.read().await; | |
println!("reader: {} lock string: {}", id, lock); | |
} | |
async fn use_write_lock(lock: Arc<RwLock<String>>, append: &str) { | |
let mut lock = lock.write().await; | |
lock.push_str(append); | |
println!("writer: lock string: {}", lock); | |
} | |
#[tokio::main] | |
async fn main() { | |
let lock = Arc::new(RwLock::new(String::from("init"))); | |
let read_lock = lock.clone(); | |
// Spin up an infinite reader thread | |
tokio::spawn(async move { | |
loop { | |
use_read_lock(1, read_lock.clone()).await; | |
sleep(Duration::from_secs(1)).await; | |
} | |
}); | |
for new_string in ["new1", "new2", "new3", "new4", "new5"] { | |
// Note we have 2 write threads | |
let write_lock = lock.clone(); | |
tokio::spawn(async move { | |
use_write_lock(write_lock, "-").await; | |
}); | |
let write_lock = lock.clone(); | |
tokio::spawn(async move { | |
use_write_lock(write_lock, new_string).await; | |
}); | |
sleep(Duration::from_secs(1)).await; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
reader: 1 lock string: init
writer: lock string: init-
writer: lock string: init-new1
reader: 1 lock string: init-new1
writer: lock string: init-new1-
writer: lock string: init-new1-new2
reader: 1 lock string: init-new1-new2
writer: lock string: init-new1-new2-
writer: lock string: init-new1-new2-new3
reader: 1 lock string: init-new1-new2-new3
writer: lock string: init-new1-new2-new3-
writer: lock string: init-new1-new2-new3-new4
reader: 1 lock string: init-new1-new2-new3-new4
writer: lock string: init-new1-new2-new3-new4-
writer: lock string: init-new1-new2-new3-new4-new5
reader: 1 lock string: init-new1-new2-new3-new4-new5