gpt4 book ai didi

rust - 从 MPSC channel 成功接收后进程永不退出

转载 作者:行者123 更新时间:2023-12-03 11:43:16 33 4
gpt4 key购买 nike

代码如下:

use std::thread;
use std::sync::mpsc;

fn main() {

//spawn threads
let (tx, rx) = mpsc::channel();
for mut i in 0 .. 10 {
let txc = tx.clone(); //clone from the main sender
thread::spawn( move || {
i += 20;
println!("Sending: {}", i);
txc.send(i).unwrap_or_else(|e| {
eprintln!("{}", e);
});
});
}

for received in rx {
println!("Received: {}", received);
}

}

代码成功运行,但挂起,进程最终没有退出。

我认为这可能与关闭 channel 端有关,我尝试通过 tx.drop()rx.drop() 删除,但编译器给出了错误.

我在这里做错了什么?

最佳答案

tx在你的主线程中直到 main 结束才被丢弃功能,和rx在删除所有发件人之前不会关闭。

要解决此问题,您可以使用 <a href="https://doc.rust-lang.org/std/mem/fn.drop.html" rel="noreferrer noopener nofollow">drop</a>(tx) 手动删除它启动所有线程后:

use std::thread;
use std::sync::mpsc;

fn main() {

//spawn threads
let (tx, rx) = mpsc::channel();
for mut i in 0 .. 10 {
let txc = tx.clone(); //clone from the main sender
thread::spawn( move || {
i += 20;
println!("Sending: {}", i);
txc.send(i).unwrap_or_else(|e| {
eprintln!("{}", e);
});
});
}

// drop tx manually, to ensure that only senders in spawned threads are still in use
drop(tx);

for received in rx {
println!("Received: {}", received);
}

}

关于rust - 从 MPSC channel 成功接收后进程永不退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61364917/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com