2

私は学校のプロジェクトに取り組んでいます(質問で私の制限を説明しています)。私の質問は、NACHOS でセマフォなしでロックを実装する方法です。NACHOS固有の回答は素晴らしいですが、私が探しているのは正しい方向へのプッシュです. これまでのところ、私の理解では、モニターはセマフォ (実際にはミューテックス) を使用するロックを使用しています。当初、セマフォをモニターに置き換えてロックを実装することを考えましたが、それは意味がありませんでした。

4

3 に答える 3

0

ロックは Thread:Sleep で実装できます。

class Lock {
  public:
    Lock(char* debugName);          // initialize lock to be FREE
    ~Lock();                // deallocate lock
    char* getName() { return name; }    // debugging assist

    void Acquire(); // these are the only operations on a lock
    void Release(); // they are both *atomic*

    bool isHeldByCurrentThread() { return (thread == currentThread); }  // true if the current thread
                    // holds this lock.  Useful for
                    // checking in Release, and in
                    // Condition variable ops below.

  private:
    char* name;             // for debugging
    // plus some other stuff you'll need to define
    Thread *thread;     //the thread who holds this lock
    enum value {FREE, BUSY};
    List *queue;
};

Lock::Lock(char* debugName):name(debugName), thread(NULL), value(FREE), queue(new List())
{ }
Lock::~Lock()
{
    delete queue;
}
void Lock::Acquire()
{
    IntStatus oldLevel = interrupt->SetLevel(IntOff);   // disable interrupts
    if (value == BUSY) {
        queue->Append((void *)currentThread);
        currentThread->Sleep();
    }
    value = BUSY;
    thread = currentThread;
    (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, consuming the V immediately
        scheduler->ReadyToRun(nextThread);
    value = FREE;
    (void) interrupt->SetLevel(oldLevel);   // re-enable interrupts
}
于 2012-12-08T06:13:26.677 に答える
0

ビジー待機を行い、セマフォを必要としないスピンロックについて考えたいと思うかもしれませんが、ユニプロセッサではスピンロックは使用されません。

于 2012-02-16T00:40:36.993 に答える