加载中...
第三次Rust
发表于:2022-05-31 | 分类: code
字数统计: 185 | 阅读时长: 1分钟 |

写这多线程猜数字打通我十年脑血栓

现在是凌晨两点,它终于什么panic都不报了

use rand::Rng;
use std::cmp::Ordering;
use std::sync::mpsc;
use std::thread;

fn main() {
    let (ex_tx, ex_rx): (mpsc::Sender<i32>, mpsc::Receiver<i32>) = mpsc::channel();
    let (gu_tx, gu_rx) = mpsc::channel();
    
    println!("Guess the number!");

    thread::spawn(move || {
        let secert_number: i32 = rand::thread_rng().gen_range(1..101);
        loop {
            let number = match ex_rx.recv() {
                Ok(t) => t,
                Err(_) => break,
            };
            gu_tx.send(number.cmp(&secert_number)).unwrap();
        }
    });

    let guessing_handle = thread::spawn(move || -> i32 {
        let mut minimum = 0;
        let mut maximum = 100;
        let mut middle;
        loop {
            middle = minimum + (maximum - minimum) / 2;
            ex_tx.send(middle).unwrap();
            match gu_rx.recv().unwrap() {
                Ordering::Greater => {
                    println!("{}太大了", middle);
                    maximum = middle;
                }
                Ordering::Less => {
                    println!("{}太小了", middle);
                    minimum = middle;
                }
                Ordering::Equal => break middle,
            }
        }
    });
    println!("{}是对的", guessing_handle.join().unwrap());
}
上一篇:
Python基础
下一篇:
第二次Rust
本文目录
本文目录