我正在研究一个学校项目(解释我在问题中的限制)。我的问题是如何在NACHOS中实现没有信号量的锁。虽然NACHOS的具体答案会很棒,但我所期待的是推动正确的方向。到目前为止,根据我的理解,监视器使用使用信号量的锁(实际上是互斥锁)。最初我们考虑用监视器替换信号量来实现锁,但是,这没有意义。
答案 0 :(得分:0)
你可能想要考虑那些忙于等待并且不需要信号量的自旋锁。但是在单处理器中没有使用自旋锁。
答案 1 :(得分:0)
Lock可以通过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
}
答案 2 :(得分:0)
首先检查锁的当前持有者是否是当前线程。然后使用中断开关和睡眠来实现锁定。线程从休眠状态唤醒后,应再次检查锁是忙还是空,因为唤醒线程只会将其传递到就绪队列。其他一些线程可能会在此线程获取锁之前再次获取锁。
void Lock::Acquire() {
ASSERT(!isHeldByCurrentThread()); // cannot acquire a lock twice
IntStatus oldLevel = interrupt->SetLevel(IntOff); // disable interrupts
while (freeOrBusy == 'b') {
queue->Append((void *)currentThread);
currentThread->Sleep();
}
freeOrBusy = 'b';
currentHolder = currentThread;
(void) interrupt->SetLevel(oldLevel); // re-enable interrupts
}
void Lock::Release() {
ASSERT(isHeldByCurrentThread());
IntStatus oldLevel = interrupt->SetLevel(IntOff);
freeOrBusy = 'f';
currentHolder = NULL;
Thread *thread = (Thread *)queue->Remove(); // "queue" is the list of threads waiting
if (thread != NULL) // make thread ready
scheduler->ReadyToRun(thread);
(void) interrupt->SetLevel(oldLevel);
}