Advertisement
everblut

Lock

Sep 14th, 2011
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. public class Lock {
  2.     /**
  3.      * Allocate a new lock. The lock will initially be free.
  4.      */
  5.     public Lock() {
  6.     }
  7.  
  8.     /**
  9.      * Atomically acquire this lock. The current thread must not already hold
  10.      * this lock.
  11.      */
  12.     public void acquire() {
  13.     Lib.assertTrue(!isHeldByCurrentThread());
  14.  
  15.     boolean intStatus = Machine.interrupt().disable();
  16.     KThread thread = KThread.currentThread();
  17.  
  18.     if (lockHolder != null) {
  19.         waitQueue.waitForAccess(thread);
  20.         KThread.sleep();
  21.     }
  22.     else {
  23.         waitQueue.acquire(thread);
  24.         lockHolder = thread;
  25.     }
  26.  
  27.     Lib.assertTrue(lockHolder == thread);
  28.  
  29.     Machine.interrupt().restore(intStatus);
  30.     System.out.println(" acquire successful by thread: "+ KThread.currentThread());
  31.     }
  32.  /**
  33.      * Atomically release this lock, allowing other threads to acquire it.
  34.      */
  35.     public void release() {
  36.     Lib.assertTrue(isHeldByCurrentThread());
  37.  
  38.     boolean intStatus = Machine.interrupt().disable();
  39.  
  40.     if ((lockHolder = waitQueue.nextThread()) != null)
  41.         lockHolder.ready();
  42.    
  43.     Machine.interrupt().restore(intStatus);
  44.     System.out.println(" release successful by thread: "+ KThread.currentThread());
  45.     }
  46.  
  47.     /**
  48.      * Test if the current thread holds this lock.
  49.      *
  50.      * @return  true if the current thread holds this lock.
  51.      */
  52.     public boolean isHeldByCurrentThread() {
  53.     return (lockHolder == KThread.currentThread());
  54.     }
  55.  
  56.     private KThread lockHolder = null;
  57.     private ThreadQueue waitQueue =
  58.     ThreadedKernel.scheduler.newThreadQueue(true);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement