Skip to content

Instantly share code, notes, and snippets.

@MatiasVara
Last active August 13, 2023 14:11
Show Gist options
  • Save MatiasVara/7cd8008842e61a4d621a48bcf04e676b to your computer and use it in GitHub Desktop.
Save MatiasVara/7cd8008842e61a4d621a48bcf04e676b to your computer and use it in GitHub Desktop.
This is just an example of async in Rust but it may be wrong. I would like to have something that executes in its own context without using a thread.
use std::time::Duration;
use async_std::task;
use std::{thread, time};
// this is something that will take some time
// to execute so we execute it as an async function
// to not block the main thread. This function must not block
async fn do_sleep(val: u32) {
task::sleep(Duration::from_secs(3)).await;
println!("hello, world! {}", val);
}
// why main is not async? is it this ok?
// see https://book.async.rs/concepts/tasks.html
fn main() {
let ten_millis = time::Duration::from_millis(2000);
for i in 0..5 {
// This function is similar to std::thread::spawn, except it spawns an asynchronous task
// I do not care the value of this return
task::spawn (
async move {
do_sleep(i).await
}
);
println!("after async");
// this simulates an external event in the main thread
thread::sleep(ten_millis);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment