Rust中的并发

std::thread

use std::{thread::{self, JoinHandle, sleep}, time::Duration};

fn main() -> std::io::Result<()> {
    let jh: JoinHandle<i32> = thread::spawn(|| {
        sleep(Duration::from_millis(3000));
        88
    });
    let a: i32 = jh.join().unwrap();
    println!("Hello, world! {}", a);
    Ok(())
}

sync::mpsc::channel

use std::{sync::mpsc::channel, thread::sleep, time::Duration};
use std::thread;

fn main() -> () {
    let (sender, receiver) = channel();

    // Spawn off an expensive computation
    // 产生昂贵的计算
    thread::spawn(move || {
        sender.send(get_result()).unwrap();
    });

    // Do some useful work for awhile
    // 暂时做一些有用的工作

    // Let's see what that answer was
    // 让我们看看答案是什么
    println!("{:?}", receiver.recv().unwrap());
}

fn get_result() -> i32 {
    sleep(Duration::from_millis(3000));
    88
}

END

posted @ 2021-04-29 09:20  develon  阅读(167)  评论(0编辑  收藏  举报