【原】面试题:锁的实现原理

忙等待就不说了。

参考nachos虚拟操作系统,给出锁的实现:

void Lock::Acquire()
{
    IntStatus oldLevel = interrupt->SetLevel(IntOff);    // disable interrupts
    while (value == BUSY) { // Here we must use while.
        queue->Append((void *)currentThread); // put thread into the waitqueue.
        currentThread->Sleep();
    }
    value = BUSY;
    (void) interrupt->SetLevel(oldLevel);    // re-enable interrupts
}

void Lock::Release()
{
    Thread *nextThread;
    IntStatus oldLevel = interrupt->SetLevel(IntOff);    // disable interrupts
    nextThread = (Thread *)queue->Remove();
    if (nextThread != NULL)       // make thread ready
        scheduler->ReadyToRun(nextThread);
    value = FREE;
    (void) interrupt->SetLevel(oldLevel);    // re-enable interrupts
}
原文地址:https://www.cnblogs.com/xmuliushuo/p/3299620.html