rust多線程和異步編程
多線程
use std::thread;
fn main() {
println!("Hello, world!");
get_two_sites();
}
fn download(url: &str)
{
println!("{}", url);
}
fn get_two_sites() {
// 創建兩個線程分別執行各自的下載任務
let thread_one = thread::spawn(|| download("https:://www.foo.com"));
let thread_two = thread::spawn(|| download("https:://www.bar.com"));
// 等待兩個線程完成任務
thread_one.join().unwrap();
thread_two.join().unwrap();
}
異步編程
// `block_on` blocks the current thread until the provided future has run to
// completion. Other executors provide more complex behavior, like scheudling
// multiple futures onto the same thread.
use futures::executor::block_on;
async fn hello_world() {
println!("hello, world!");
}
fn main() {
let future = hello_world(); // Nothing is printed
block_on(future); // `future` is run and "hello, world!" is printed
}
tokio線程調度設計
有時間看看,很不錯
https://tokio.rs/blog/2019-10-scheduler/
