Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Lock {
- /**
- * Allocate a new lock. The lock will initially be free.
- */
- public Lock() {
- }
- /**
- * Atomically acquire this lock. The current thread must not already hold
- * this lock.
- */
- public void acquire() {
- Lib.assertTrue(!isHeldByCurrentThread());
- boolean intStatus = Machine.interrupt().disable();
- KThread thread = KThread.currentThread();
- if (lockHolder != null) {
- waitQueue.waitForAccess(thread);
- KThread.sleep();
- }
- else {
- waitQueue.acquire(thread);
- lockHolder = thread;
- }
- Lib.assertTrue(lockHolder == thread);
- Machine.interrupt().restore(intStatus);
- System.out.println(" acquire successful by thread: "+ KThread.currentThread());
- }
- /**
- * Atomically release this lock, allowing other threads to acquire it.
- */
- public void release() {
- Lib.assertTrue(isHeldByCurrentThread());
- boolean intStatus = Machine.interrupt().disable();
- if ((lockHolder = waitQueue.nextThread()) != null)
- lockHolder.ready();
- Machine.interrupt().restore(intStatus);
- System.out.println(" release successful by thread: "+ KThread.currentThread());
- }
- /**
- * Test if the current thread holds this lock.
- *
- * @return true if the current thread holds this lock.
- */
- public boolean isHeldByCurrentThread() {
- return (lockHolder == KThread.currentThread());
- }
- private KThread lockHolder = null;
- private ThreadQueue waitQueue =
- ThreadedKernel.scheduler.newThreadQueue(true);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement