Untitled
unknown
rust
2 years ago
1.5 kB
11
Indexable
use futures::executor::block_on;
use futures::future::join_all;
use async_std::task;
use std::{thread, time};
async fn task_1() -> Result<i32, ()> {
let mut total = 0;
for _ in 1..15 {
total += 1;
}
thread::sleep(time::Duration::from_secs(1));
println!("Finished 1");
Ok(total)
}
async fn task_2() -> Result<i32, ()> {
let mut total = 0;
for _ in 1..5 {
total += 1;
}
thread::sleep(time::Duration::from_secs(2));
println!("Finished 2");
Ok(total)
}
async fn task_spawner() -> Result<i32, ()> {
// Executa as tarefas de modo assíncrono.
let tasks = vec![
task::spawn(task_1()),
task::spawn(task_2()),
];
println!("Sleeping...");
thread::sleep(time::Duration::from_secs(3));
// Aguarda a finalização das tasks e captura seu resultado.
let results = join_all(tasks).await;
let mut total = 0;
for item in results {
match item {
Ok(value) => {
println!("value: {value}");
total += value;
},
Err(()) => println!("Error"),
}
}
println!("total: {}", total);
Ok(total)
}
fn main() {
let total = block_on(task_spawner()).unwrap();
println!("total block: {total}");
}
/*
Output:
Sleeping...
Finished 1
Finished 2
value: 14
value: 4
total: 18
total block: 18
*/
Editor is loading...