作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个循环:
let grace = 2usize;
for i in 0..100 {
if i % 10 == 0 {
expensive_function()
} else {
cheap_function()
}
}
目标是当它到达
expensive_function()
时,它异步运行并允许
grace
直到等待的进一步迭代次数
expensive_function()
.
expensive_function()
在迭代 10 时触发,然后它可以在需要等待
expensive_function()
之前运行迭代 11 和 12在迭代 10 上运行以完成继续。
expensive_function()
有效地:
fn expensive_function(&b) -> Vec<_> {
return b.iter().map(|a| a.inner_expensive_function()).collect();
}
因此,我计划在此功能中使用多线程。
最佳答案
当您开始昂贵的计算时,将产生的 future 存储在一个变量中,以及等待结果的截止时间。在这里,我使用 Option
元组:
use std::{thread, time::Duration};
use tokio::task; // 0.2.21, features = ["full"]
#[tokio::main]
async fn main() {
let grace_period = 2usize;
let mut pending = None;
for i in 0..50 {
if i % 10 == 0 {
assert!(pending.is_none(), "Already had pending work");
let future = expensive_function(i);
let deadline = i + grace_period;
pending = Some((deadline, future));
} else {
cheap_function(i);
}
if let Some((deadline, future)) = pending.take() {
if i == deadline {
future.await.unwrap();
} else {
pending = Some((deadline, future));
}
}
}
}
fn expensive_function(n: usize) -> task::JoinHandle<()> {
task::spawn_blocking(move || {
println!("expensive_function {} start", n);
thread::sleep(Duration::from_millis(500));
println!("expensive_function {} done", n);
})
}
fn cheap_function(n: usize) {
println!("cheap_function {}", n);
thread::sleep(Duration::from_millis(1));
}
这将生成输出
cheap_function 1
expensive_function 0 start
cheap_function 2
expensive_function 0 done
cheap_function 3
cheap_function 4
cheap_function 5
由于您没有提供
expensive_function
的定义和
cheap_function
,我已经提供了合适的。
sleep
调用
cheap_function
.没有它,我的操作系统永远不会安排昂贵的线程,直到轮询它为止,从而有效地删除了任何并行工作。在更大的程序中,操作系统很可能只是因为
cheap_function
将完成更多的工作而调度线程。 .您也可以使用
thread::yield_now
达到同样的效果。
关于asynchronous - 如何在启动异步操作和在循环中等待其结果之间有一个宽限期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62519502/
这些是我的宽限期设置(/etc/varnish/default.vcl) sub vcl_recv { .... set req.grace = 360000s; ... } sub vcl_fetc
Apple 引入了订阅宽限期。 https://developer.apple.com/app-store-connect/whats-new/?id=billinggraceperiod 我仍然无法
我总是插入数据 PRIMARY KEY ((site_name,date),time,id) 而 site_name 和 date 可以相同,这是一个驯服的字段和 id(uuid) 不同的时间。所以我
当弹性负载均衡器 (ELB) 与自动扩展组相关联时,可以指定一个宽限期,在此宽限期内,即使新 EC2 实例被 ELB 标记为不正常,也不会终止。是否可以指定一个类似的宽限期,在此期间新的 ECS 任务
我是一名优秀的程序员,十分优秀!