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

posted on 2020-04-10 13:58  cutepig  阅读(1871)  评论(0编辑  收藏  举报

导航