Skip to content

31.4 crossbeam

crossbeam 是 Rust 核心组的另外一位重要成员 Aaron Turon 牵头开发的。它包含了并行开发的很多方面的功能,比如无锁数据类型,以及重新设计实现的管道。

我们知道标准库给了一份 mpsc(多生产者单消费者)管道的实现,但是它有许多缺陷。crossbeam-channel 这个库给我们提供了另外一套管道的实现方式。不仅包括 mpsc,还包括 mpmc(多生产者多消费者),而且使用便捷,执行效率也很高。

下面是一个双端管道的使用示例。它基本实现了 go 语言的内置管道功能,在执行效率上甚至有过之而无不及。

rust
extern crate crossbeam;
#[macro_use]
extern crate crossbeam_channel as channel;

use channel::{Receiver, Sender};

fn main() {
    let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"];
    let (tx, rx) = channel::bounded(1); // Make room for one unmatched send.
    let (tx, rx) = (&tx, &rx);

    crossbeam::scope(|s| {
        for name in people {
            s.spawn(move || seek(name, tx, rx));
        }
    });

    if let Ok(name) = rx.try_recv() {
        println!("No one received {}’s message.", name);
    }
}

// Either send my name into the channel or receive someone else's, whatever happens first.
fn seek<'a>(name: &'a str, tx: &Sender<&'a str>, rx: &Receiver<&'a str>) {
    select_loop! {
        recv(rx, peer) => println!("{} received a message from {}.", name, peer),
        send(tx, name) => {}, // Wait for someone to receive my message.
    }
}

Released under the MIT License