6.2 Crossbeam

Non-blocking data structures support for concurrent and parallel programming in Rust.

crossbeam::spawn is similar to the std::thread::spawn function in Rust’s standard library. The difference is that this thread is scoped, meaning that it’s guaranteed to terminate before the current stack frame goes away, allowing you to reference the parent stack frame directly.

This is ensured by having the parent thread join on the child thread before the scope exits.

extern crate crossbeam;

use std::sync::mpsc;

// #[rustr_export]
pub fn crossinr(){
    let (tx, rx) = mpsc::channel();

    let tx = tx.clone();
    crossbeam::scope(
        |scope| {
            scope.spawn(move || {
                tx.send(format!("from thread 1")).unwrap(); });
    });


    r_printf(&format!("{}", 
                    rx.recv().unwrap_or("?".into())
                    )
            );
}
rust(code = '
extern crate crossbeam;

use std::sync::mpsc;

// #[rustr_export]
pub fn crossinr(){
    let (tx, rx) = mpsc::channel();

    let tx = tx.clone();
    crossbeam::scope(
        |scope| {
            scope.spawn(move || {
                tx.send(format!("from thread 1")).unwrap(); });
    });

    r_printf(&format!("{}", 
                    rx.recv().unwrap_or("?".into())
                    )
            );
}

',depend = '
[dependencies]
rustr = "*"
crossbeam = "0.2.8"
')
#> updating cached Cargo.toml.

crossinr()
#> from thread 1