0

我有一个前向缓存,它计算一些昂贵的值。

在某些情况下,我必须对同一资源执行阻塞调用(而不是通过缓存)

在前向缓存已经在计算“消息”的情况下,我想await(阻塞调用)直到这个正在进行的计算完成。

我当前的(简单)代码的结构类似于:

struct MyStruct {
  cache : Cache // results caching
}

impl MyStruct {
  async fn forward_cache_compute(&self, identifier: &str) {
    // do some expensive computation and cache it:
    ... 
    let value = self.compute().await // .... takes 100 ms ...
    self.cache.insert(identifier, value) 
// consider if possible to save a future of compute() or conditional variable to wait upon for "identifier"
  }

  async fn compute(&self) -> ExpensiveThing {....}


  async fn get_from_cache_or_compute_if_neeeded(&self, identifier: &str) -> ExpensiveThing {
     // would like to check if the forward cache is already computing and return that value if possible (share a future?)
     if let Some(cached_value) self.cache.get(identifier) {
        // use this cached_value and don't compute
     } else if ... inflight computation is in progress... {
        //block on that 
        // can I save the future and await it from multiple places?
     }
  }
}
4

0 回答 0