如何通过Rust中的通道工作?

时间:2016-08-15 15:06:51

标签: multithreading rust channels

我对channel chapter of Rust by Example

的输出感到困惑
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

static NTHREADS: i32 = 3;

fn main() {
    // Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,
    // where `T` is the type of the message to be transferred
    // (type annotation is superfluous)
    let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();

    for id in 0..NTHREADS {
        // The sender endpoint can be copied
        let thread_tx = tx.clone();

        // Each thread will send its id via the channel
        thread::spawn(move || {
            // The thread takes ownership over `thread_tx`
            // Each thread queues a message in the channel
            thread_tx.send(id).unwrap();

            // Sending is a non-blocking operation, the thread will continue
            // immediately after sending its message
            println!("thread {} finished", id);
        });
    }

    // Here, all the messages are collected
    let mut ids = Vec::with_capacity(NTHREADS as usize);
    for _ in 0..NTHREADS {
        // The `recv` method picks a message from the channel
        // `recv` will block the current thread if there no messages available
        ids.push(rx.recv());
    }

    // Show the order in which the messages were sent
    println!("{:?}", ids);
}

使用默认NTHREADS = 3,我得到以下输出:

thread 2 finished
thread 1 finished
[Ok(2), Ok(1), Ok(0)]

为什么println!("thread {} finished", id);循环中的for按相反的顺序打印? thread 0 finished去哪儿了?

当我改为NTHREADS = 8时,发生了一些更神秘的事情:

thread 6 finished
thread 7 finished
thread 8 finished
thread 9 finished
thread 5 finished
thread 4 finished
thread 3 finished
thread 2 finished
thread 1 finished
[Ok(6), Ok(7), Ok(8), Ok(9), Ok(5), Ok(4), Ok(3), Ok(2), Ok(1), Ok(0)]

打印命令使我更加困惑,线程0总是丢失。如何解释这个例子?

我在不同的计算机上试过这个并得到了相同的结果。

1 个答案:

答案 0 :(得分:7)

没有保证线程的顺序或它们之间的任何协调,因此它们将执行并以任意顺序将结果发送到通道。这就是整点 - 如果它们是独立的,你可以使用多个线程。

主线程从频道中提取N值,将它们放入Vec,打印Vec并退出。

主线程等待子线程在退出之前完成。丢失的打印由最后一个子线程将值发送到通道,主线程读取它(结束for循环),然后程序退出来解释。线程永远不可能打印完毕。

在主线程恢复并退出之前,最后一个线程也有可能运行并打印出来。

根据CPU或操作系统的数量,每个方案可能或多或少可能,但两者都是正确运行程序。

修改为等待线程的代码版本显示不同的输出:

use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

static NTHREADS: i32 = 3;

fn main() {
    // Channels have two endpoints: the `Sender<T>` and the `Receiver<T>`,
    // where `T` is the type of the message to be transferred
    // (type annotation is superfluous)
    let (tx, rx): (Sender<i32>, Receiver<i32>) = mpsc::channel();

    let handles: Vec<_> = (0..NTHREADS).map(|id| {
        // The sender endpoint can be copied
        let thread_tx = tx.clone();

        // Each thread will send its id via the channel
        thread::spawn(move || {
            // The thread takes ownership over `thread_tx`
            // Each thread queues a message in the channel
            thread_tx.send(id).unwrap();

            // Sending is a non-blocking operation, the thread will continue
            // immediately after sending its message
            println!("thread {} finished", id);
        })
    }).collect();

    // Here, all the messages are collected
    let mut ids = Vec::with_capacity(NTHREADS as usize);
    for _ in 0..NTHREADS {
        // The `recv` method picks a message from the channel
        // `recv` will block the current thread if there no messages available
        ids.push(rx.recv());
    }

    // Show the order in which the messages were sent
    println!("{:?}", ids);

    // Wait for threads to complete
    for handle in handles {
        handle.join().expect("Unable to join");
    }
}

注意,在这种情况下,主线程如何在最后一个线程退出之前打印

thread 2 finished
thread 1 finished
[Ok(2), Ok(1), Ok(0)]
thread 0 finished

这四行也可以在任何顺序中发生:在主线程打印之前或之后没有任何原因可以打印任何子线程。