0

我正在用 java 做 NACHOS 第 3 阶段项目(缓存和虚拟内存)。我在实现下面给出的功能时有些困惑:

/**
 * Restore the state of this process after a context switch. Called by
 * UThread.restoreState()
 */

public void restoreState() {
    // Invalidate all TLB entries;
    for(int i=0; i < Machine.processor().getTLBSize(); i++){
        Lib.debug(dbgVM, "Invalidating TLB on context switch.");
        TranslationEntry entry = Machine.processor().readTLBEntry(i);
        entry.valid = false;
        Machine.processor().writeTLBEntry(i, entry);
    }

    syncPageTable();
}

/**
 * Called when the process is context switched in. Synchs the process
 * pagetable with the global one so that read/writeVirtualMemory calls
 * can proceed as they would normally in the UserProcess class.
 */
private void syncPageTable(){
    for(TranslationEntry e : pageTable){
        TranslationEntry f = vmk.lookupAddress(super.getPid(), e.vpn);
        if(f == null || f.valid == false){
            e.valid = false;
        }else if(f != null){
            f.valid = true;
        }
    }
}

这里,vmk = (VMKernel)Kernel.kernel; . 我还没有理解syncPageTable()函数。TranslationEntry e : pageTable在 for 子句中的含义是什么,以及 if-else 块实际检查的内容是什么?

4

1 回答 1

0
for( TranslationEntry e : pageTable ) { /* block */ }

这称为“for each”语句。它遍历 pageTable 中的每个 TranslationEntry 并执行块中的语句。当前条目名为“e”。阅读 javadoc 了解更多详细信息。

正式化:

for( <type> <variable-name> : <name of the container containing <type> entries> ) {}

关于块中的语句:该函数lookupAddress()看起来像是返回 aTranslationEntrynull. 您需要首先检查null,因为||如果第一部分为真,则不会评估语句的第二部分。如果你省略了这个测试nullf.valid会引发一个空指针异常。

现在: else if( f != null ): 如果 f 为空或 f 无效,您的第一个 if 语句为假。要知道发生了哪种情况,您必须测试一个的倒数。您也可以进行测试if( f.valid == true ),但和以前一样,这会引发空指针异常。所以这真正要问的是:if( f != null && f.valid == true ).

于 2015-12-18T11:01:24.747 回答