Three threads print 1-100 in turn

Time:2021-11-27
use std::sync::mpsc;
use std::thread;

fn main() {
    let (s1, r1) = mpsc::channel::<usize>(); //  S1 tells the next thread to print 3N + 1, and R1 receives the print number of 3N + 1
    let (s2, r2) = mpsc::channel::<usize>(); //  S2 tells the next thread to print 3N + 2, and R2 receives the print number of 3N + 2
    let (s3, r3) = mpsc::channel::<usize>(); //  S3 tells the next thread to print 3N + 3, and R3 receives the print number of 3N + 3

    const MAX_PINRT: usize = 100;

    thread::spawn(move || {
        let id = thread::current().id();
        loop {
            if let Ok(message) = r2.recv() {
                println!("thread {:?} print: {}", id, message);
                if message < MAX_PINRT {
                    s3.send(message + 1).unwrap();
                } else {
                    break;              //        Print complete exit
                }
            } else {
                break;                  //        Output complete exit 
            }
        }
    });

    thread::spawn(move || {
        let id = thread::current().id();
        for val in r3 {
            println!("thread {:?} print: {}", id, val);
            if val < MAX_PINRT {
                s1.send(val + 1).unwrap();
            } else {
                break;
            }
        }
    });
    let id = thread::current().id();
    s2.send(1).unwrap();
    for val in r1 {
        println!("thread {:?} print: {}", id, val);
        if val < MAX_PINRT {
            s2.send(val + 1).unwrap();
        } else {
            break;
        }
    }
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article