c - C中Cache方法的理解

标签 c caching

我对缓存很陌生,我想知道是否有人可以帮助我理解这种方法。如果它实际上返回整个缓存 block 指针,它如何获取标签? *bIndex 在这里做什么,它的缩写是什么意思?

cacheBlock* getTag(int index, int tag, int *bIndex) {
  int i;

  for (i = 0; i < assoc; i ++ ) {   
    if (cache[index].block[i].tag == tag) {
      cacheBlock *targetBlock = &cache[index].block[i];
      *bIndex = i;
      return targetBlock;
    }
  }
  *bIndex = -1;
  return NULL;
}

最佳答案

分析如下:

cacheBlock* getTag(int index, int tag, int *bIndex) 
{
  int i;

  // walk all blocks in cache[index] block[] table
  for (i = 0; i < assoc; i ++ ) 
  {
    // if the block association at this index matches this tag,
    //  then the block we're looking for is in the cache.   
    if (cache[index].block[i].tag == tag) 
    {
      // setup return value (this is unneeded, btw. simply setting
      //  *bIndex and returning (cache[index].block+i) would work).
      cacheBlock *targetBlock = &cache[index].block[i];

      // set out-param to inform them which block[i].tag matched in the
      //  block being returned by address. either this is actually not
      //  needed, or this is a bug, since we already return the precise
      //  block[i] entry by address (see above). the caller may like
      //  knowing *which* block[] entry matched for whatever reason.
      *bIndex = i;

      // return the matching cache[index].block[i] address
      return targetBlock;
    }
  }

  // no match condition. set offset to (-1) and return NULL.
  *bIndex = -1;
  return NULL;
}

话虽如此,我相信您应该检查此代码的调用者,因为他们收到的 block[] 条目已经偏移到他们正在寻找的精确匹配项。即返回的指针不需要 *bIndex 偏移量。如果他们使用它来索引返回地址的偏移量,即他们的代码看起来像这样:

int bIndex = 0;
cacheBlock *pEntry = getTag(cache, tag, &bIndex);
if (pEntry != NULL)
{
    // do something with pEntry[bIndex]
}

这可能是一个错误,也许他们打算返回 cache[index].block,而不是 cache[index].block+i

关于c - C中Cache方法的理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13311215/

相关文章:

java - 在应用程序启动时缓存数据库表数据

macos - 图像缓存的平面或嵌套目录结构?

database - 在 Web 应用程序中缓存适量的数据 - 数据库还是平面文件?

c - 在退出时关闭文件描述符是一种好习惯吗

c - 金字塔分割 OpenCV

C/C++ I18N mbstowcs 问题

SO_KEEPALIVE 的 C 套接字编程

c++ - C/C++ 只比较一次

c# - Best-practice caching : monolithic vs. 细粒度缓存数据

javascript 无法缓存?