Created
September 7, 2022 06:17
-
-
Save alaingilbert/98190b42d7bf70a6eba2194298a95b53 to your computer and use it in GitHub Desktop.
rust bankers
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
[package] | |
name = "rs-bankers" | |
version = "0.1.0" | |
edition = "2021" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
tokio = { version = "1.21.0", features = ["full"] } | |
tokio-scoped = "0.2.0" |
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::Mutex; | |
use tokio::time::{Duration, Instant, sleep}; | |
struct Banker {} | |
impl Banker { | |
fn new() -> Self { | |
Self{} | |
} | |
async fn work(&self, tasks: Arc<Mutex<Vec<Task>>>, start: Instant) { | |
loop { | |
let task_opt = tasks.lock().await.pop(); | |
match task_opt { | |
Some(task) => { | |
println!("tasks {} started after {:?}", task.name, Instant::now().duration_since(start)); | |
sleep(task.time_to_complete).await; | |
}, | |
None => break, | |
} | |
} | |
} | |
} | |
struct Task { | |
name: String, | |
time_to_complete: Duration, | |
} | |
impl Task { | |
fn new(name: &str, dur: Duration) -> Self { | |
Self { name: name.to_owned(), time_to_complete: dur } | |
} | |
} | |
#[tokio::main] | |
async fn main() { | |
let tasks = vec![ | |
Task::new("7", Duration::from_secs(1)), | |
Task::new("6", Duration::from_secs(6)), | |
Task::new("5", Duration::from_secs(5)), | |
Task::new("4", Duration::from_secs(4)), | |
Task::new("3", Duration::from_secs(3)), | |
Task::new("2", Duration::from_secs(2)), | |
Task::new("1", Duration::from_secs(1)), | |
]; | |
let start = Instant::now(); | |
tokio_scoped::scope(|scope| { | |
let tasks = Arc::new(Mutex::new(tasks)); | |
let num_bankers = 3; | |
for _ in 0..num_bankers { | |
let tasks = tasks.clone(); | |
let start = start.clone(); | |
scope.spawn(async move { | |
Banker::new().work(tasks, start).await; | |
}); | |
} | |
}); | |
println!("All done after {:?}", Instant::now().duration_since(start)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment