Concurrency #2

https://doc.rust-lang.org/book/concurrency.html

並行処理続き。channelについて。rxからtxにデータが渡るまで、tx側は処理を待つ。

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

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

    for i in 0..10 {
        let tx = tx.clone();

        thread::spawn(move || {
            let answer = i * i;

            tx.send(answer).unwrap();
        });
    }

    for _ in 0..10 {
        println!("{}", rx.recv().unwrap());
    }

    let handle = thread::spawn(move || {
        panic!("oops!");
    });
    let result = handle.join();
    assert!(result.is_err());
}
$ cargo run
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/5_6_concurrency`
0
1
4
16
25
9
64
36
81
49
thread '<unnamed>' panicked at 'oops!', src/main.rs:22
note: Run with `RUST_BACKTRACE=1` for a backtrace.