V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
52funny
V2EX  ›  问与答

请教一个 rust 问题!

  •  
  •   52funny · 299 天前 · 630 次点击
    这是一个创建于 299 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有一段代码不是很理解,为什么第一段代码会卡住,不会出结果?

    use futures; // 0.3.28
    use futures::future;
    use futures::executor::block_on;
    use futures::channel::mpsc::unbounded;
    use futures::pin_mut;
    use futures::SinkExt;
    use futures::StreamExt;
    use futures::future::Either;
    
    
    fn main() {
        let (mut tx, rx) = unbounded::<i32>(); 
        let x = async {
            for i in 0..100 {
                tx.send(i).await.expect("send failed");
            }
        };
        let y = rx.collect::<Vec<_>>();
        pin_mut!(x, y);
        block_on(async {
            match future::select(x, y).await {
                Either::Left((_, y)) => {
                    let res = y.await;
                    println!("{:?}", res);
                },
                Either::Right((res, _)) => {
                    println!("{:?}", res);
                }
            }
        });
    }
    

    而这一段代码可以运行,不会卡住

    use futures; // 0.3.28
    use futures::future;
    use futures::executor::block_on;
    use futures::channel::mpsc::unbounded;
    use futures::pin_mut;
    use futures::SinkExt;
    use futures::StreamExt;
    use futures::future::Either;
    
    
    fn main() {
        let (mut tx, rx) = unbounded::<i32>(); 
        let x = async move {
            for i in 0..100 {
                tx.send(i).await.expect("send failed");
            }
        };
        let y = rx.collect::<Vec<_>>();
        pin_mut!(x, y);
        block_on(async {
            match future::select(x, y).await {
                Either::Left((_, y)) => {
                    let res = y.await;
                    println!("{:?}", res);
                },
                Either::Right((res, _)) => {
                    println!("{:?}", res);
                }
            }
        });
    }
    

    rust playgroud

    3 条回复    2023-07-03 21:05:44 +08:00
    cfeitong
        1
    cfeitong  
       299 天前 via Android   ❤️ 1
    第一段代码,tx 在 main 结束后才会 drop 。第二段代码,tz 在 x 结束后会 drop 。因此,第一段代码中 block_on 永不结束,原因是 rx 没有收到通道关闭的信息,一直在等待下一个数据。第二段代码,x 执行完毕后,tx 被 drop ,rx 收到通道关闭的信息,于是结束了执行。
    cfeitong
        2
    cfeitong  
       299 天前 via Android
    @cfeitong 有个笔误:tz->tx
    52funny
        3
    52funny  
    OP
       299 天前
    @cfeitong #1 谢谢大佬的解释。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   879 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 21:06 · PVG 05:06 · LAX 14:06 · JFK 17:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.