Rust编程语言-16-无惧并发

使用线程并行执行代码

使用spawn 创建线程

use std::thread;
use std::time::Duration;

fn main() {
    let handler = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
    handler.join().unwrap();
}

使用thread::spawn,传递一个闭包closure进来
join()方法确保handler的线程都能执行完

使用move在线程间传递数据

use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
}

上面的代码使得在线程的spawn的闭包的逻辑代码里,可以捕获变量v的值并使用它

使用消息在线程间传递数据

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let val = String::from("hi");
        tx.send(val).unwrap();
    });

    let received = rx.recv().unwrap();
    println!("Got: {}", received);
}

标准库中的mpsc-多个producer,一个消费者

多个生产者

let (tx, rx) = mpsc::channel();

let tx1 = tx.clone();

接下来就在两个线程里在tx,tx1上发送消息,在rx上接收消息

你可能感兴趣的:(Rust编程语言-16-无惧并发)