请教一个 rust 问题!

355 天前
 52funny

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

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

692 次点击
所在节点    问与答
3 条回复
cfeitong
355 天前
第一段代码,tx 在 main 结束后才会 drop 。第二段代码,tz 在 x 结束后会 drop 。因此,第一段代码中 block_on 永不结束,原因是 rx 没有收到通道关闭的信息,一直在等待下一个数据。第二段代码,x 执行完毕后,tx 被 drop ,rx 收到通道关闭的信息,于是结束了执行。
cfeitong
355 天前
@cfeitong 有个笔误:tz->tx
52funny
355 天前
@cfeitong #1 谢谢大佬的解释。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/953645

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX