Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 当任何任务正在运行时,如何阻止异步程序终止?_Loops_Asynchronous_Events_Rust_Tokio - Fatal编程技术网

Loops 当任何任务正在运行时,如何阻止异步程序终止?

Loops 当任何任务正在运行时,如何阻止异步程序终止?,loops,asynchronous,events,rust,tokio,Loops,Asynchronous,Events,Rust,Tokio,假设我有这样的东西 async fn do_update() { // here we store it. let task = task::spawn(async { let duration = Duration::from_millis(10); let mut stream = tokio::time::interval(duration); stream.tick().await; loop {

假设我有这样的东西

async fn do_update() {
    // here we store it.
    let task = task::spawn(async {
        let duration = Duration::from_millis(10);
        let mut stream = tokio::time::interval(duration);
        stream.tick().await;
        loop {
            println!("Foo");
            stream.tick().await;
        }
    });
    // and here we await it.
    task.await;
}
如果我调用它,比如
do_update()。等待
循环将永远运行。这就是我想要的。但我不想让它成为唯一运行的东西。我只希望它阻止终止,直到任务解决

我希望每5秒运行一次事件,而不阻塞程序的其余部分。如果我把它放在程序的末尾,它就完全符合我的要求。似乎这曾经是在空闲时关闭的,但是现在提供的解决方案对我来说也不是有效的

我不能像那样实现它,因为我是在另一个任务中生成的


在一个任务生成任务的系统中,如何确保只有在没有更多任务运行时才关闭可执行文件?

我认为您正在寻找结构化并发,特别是全局隐式作用域。可悲的是,这方面的工作暂时被放弃了

同时,这里有一个可能的解决方法。调用
spawn\u keep\u alive
而不是
tokio::spawn
以执行任何应使程序保持活动状态的任务:

使用停车场::互斥;
使用std::{
未来,
sync::atomic::{AtomicU32,排序},
时间:持续时间,
};
使用tokio::{sync::oneshot,task::JoinHandle};
静态KEEPALIVE_计数:AtomicU32=AtomicU32::new(0);
静态KEEPALIVE\u发送方:Mutex=停车场::const\u Mutex(无);
pub fn spawn_keep_alive(任务:T)->JoinHandle
哪里
T:未来+发送+静态,
输出:发送+'静态,
{
KEEPALIVE\u COUNT.fetch\u add(1,Ordering::Relaxed);
东京:产卵(异步){
让结果=任务。等待;
如果KEEPALIVE\u COUNT.fetch\u sub(1,Ordering::Relaxed)==1{
让sender=KEEPALIVE\u sender.尝试锁定().unwrap().take().unwrap();
sender.send(()).unwrap();
}
结果
})
}
异步fn do_update(){
让mut stream=tokio::time::interval(持续时间::from_millis(100));
stream.tick()等待;
对于0..10中的uu{
println!(“Foo”);
stream.tick()等待;
}
繁殖\u保持\u活动(异步{
东京::时间::睡眠(持续时间::从_millis(1000))。等待;
println!(“我是Aliveee!”);
});
繁殖\u保持\u活动(异步{
东京:时间:睡眠(持续时间:从米利斯开始(2000))。等待;
println!(“别忘了我!”);
});
}
#[tokio::main]
异步fn main(){
let(send,recv)=oneshot::channel();
*保留发件人。尝试锁定()。展开()=一些(发送);
产卵保持生命(do_update());
//等待所有保持活动状态任务完成
recv.wait.unwrap();
}
KEEPALIVE\u SENDER
可能更有效,但只使用了两次)