rust多線程和異步編程


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/

有哪些modern的rust async的入門材料?

Ref

https://learnku.com/docs/async-book/2018/why_async/4787


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM