我正在努力实现一个互斥锁,而不是忙着等待。基本上,如果一个线程想要锁,它会检查Mutex是否已经被锁定,如果是的话,就让线程进入休眠状态并将它添加到FIFO队列中。当持有锁的线程去解锁Mutex时,它会检查是否有线程正在等待访问关键区域,如果是的话,从队列中删除线程并将其添加到一个“就绪”队列中,该队列控制所使用的线程的顺序。
我不能让Mutex工作,但是它下面的信号量工作得很好。有什么想法吗?谢谢。
// DOESN'T WORK
class Mutex {
Thread * thisThread;
Thread * threadWithLock;
lock() {
// disable interrupts
interrupts.disable();
// if no-one has lock, give lock to the current thread and set the lock
// else put the thread to sleep and add it to the waiting thread queue
if (lockStatus == 0) {
lock = 1
threadWithLock = thisThread;
} else {
sleepingThreads.enqueue(thisThread);
thisThread.sleep();
}
// re-enable previous interrupt status
interrupts.revert();
}
unlock() {
// disable interrupts
interrupts.disable();
// if there is a thread waiting for the lock, add it to the ready list
if (sleepingThreads.isEmpty() == false) {
Thread * t = sleepingThreads.dequeue();
t.updateStatus(READY);
threadReadyList.enqueue(t);
}
// release lock
threadWithLock = null;
lock = 0;
// re-enable previous interrupt status
interrupts.revert();
}
}
// WORKS
class Semaphore {
Thread * thisThread;
down() {
// disable interrupts
interrupts.disable();
readyCount -= 1;
if (readyCount < 0) {
sleepingThreads.enqueue(thisThread);
thisThread.sleep();
}
// re-enable previous interrupt status
interrupts.revert();
}
up () {
// disable interrupts
interrupts.disable();
readyCount += + 1;
if (readyCount <= 0) {
Thread * t = null;
t = sleepingThreads.dequeue();
t.updateStatus(READY);
threadReadyList.enqueue(t);
}
// re-enable previous interrupt status
interrupts.revert();
}
}编辑:问题是我没有将锁交给队列中等待的下一个线程。这与中断状态无关。正确解锁()如下所示。
unlock() {
// disable interrupts
interrupts.disable();
// if there is a thread waiting for the lock, add it to the ready list,
// and hand the lock over
if (sleepingThreads.isEmpty() == false) {
Thread * t = sleepingThreads.dequeue();
t.updateStatus(READY);
threadReadyList.enqueue(t);
threadWithLock = t;
} else {
//release the lock
threadWithLock = null;
lock = 0
}
// re-enable previous interrupt status
interrupts.revert();
}发布于 2014-10-20 18:38:50
问题是,我没有将锁交给等待队列中的下一个线程。这与中断状态无关。正确解锁()如下所示。
unlock() {
// disable interrupts
interrupts.disable();
// if there is a thread waiting for the lock, add it to the ready list,
// and hand the lock over
if (sleepingThreads.isEmpty() == false) {
Thread * t = sleepingThreads.dequeue();
t.updateStatus(READY);
threadReadyList.enqueue(t);
threadWithLock = t;
} else {
//release the lock
threadWithLock = null;
lock = 0
}
// re-enable previous interrupt status
interrupts.revert();
}https://stackoverflow.com/questions/26345153
复制相似问题