我有一个类型为
f: fn(x: SomeType, y: Arc<()>) -> ISupposeTheReturnTypeDoesNotMatter
在编译时(无论是否进行优化),
y
会被优化掉吗?
y
的意图是限制f
的运行实例数量,如果引用y
的次数太多,调用f
的调用者将不会调用f
,直到y
的引用计数降低为止。编辑:澄清我的意图
意图是控制正在运行的http请求的数量(由上述
f
表示),伪代码如下:let y = Arc::new(());
let all_jobs_to_be_done = vector_of_many_jobs;
loop {
while y.strong_count() < some_predefined_limit {
// we have some free slots, fill them up with instances of f,
// f is passed with a clone of y,
// so that the running of f would increase the ref count,
// and the death of the worker thread would decrease the ref count
let work = all_jobs_to_be_done.pop();
let ticket = y.clone();
spawn_work(move || {f(work, ticket)});
}
sleep_for_a_few_seconds();
}
这种看似不太正常的解决方案是因为我找不到符合我的需求的库(使用有限数量的异步(tokio)工作线程消耗一个变化中的工作队列,并在作业失败时重新排队)。
Arc
传递给被调用方?就像你所说,它在那里没有被使用...我不明白在函数签名中保留它的目的。 - eggyalArc
传递给函数的情况下实现相同的效果,而是在函数返回后在生成的闭包中丢弃它。 - eggyal