我对缓存很陌生,我想知道是否有人可以帮助我理解这种方法。如果它实际上返回整个缓存 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/