有一段代码不是很理解,为什么第一段代码会卡住,不会出结果?
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);
            }
        }
    });
}
|      1cfeitong      2023-07-03 18:01:40 +08:00 via Android  1 第一段代码,tx 在 main 结束后才会 drop 。第二段代码,tz 在 x 结束后会 drop 。因此,第一段代码中 block_on 永不结束,原因是 rx 没有收到通道关闭的信息,一直在等待下一个数据。第二段代码,x 执行完毕后,tx 被 drop ,rx 收到通道关闭的信息,于是结束了执行。 |