Advertisement
CSenshi

OOP - f2019 Buffer (revised)

Jul 18th, 2019
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.64 KB | None | 0 0
  1. public class Buffer{
  2.  
  3.     private Mutex m1, m2;
  4.     private int n;
  5.     private in k;  
  6.  
  7.     private ReentrantLock lock;
  8.     object obj;
  9.    
  10.     public Buffer(int n, int k){
  11.         lock = new ReentrantLock();
  12.         m = new Mutex();
  13.         this.n = n;
  14.         this.k = k;
  15.         obj = new Object();
  16.     }
  17.  
  18.     public void await() {
  19.         lock.lock();
  20.         m2.lock(); 
  21.  
  22.  
  23.         // atomic Substraction
  24.         m1.lock();
  25.         n--;
  26.         m1.unlock();
  27.         while(n > 0 && k > 0){
  28.             m2.unlock();           
  29.             lock.unlock();
  30.  
  31.             obj.wait();        
  32.  
  33.             lock.lock();
  34.             m2.lock(); 
  35.         }
  36.         m2.unlock();
  37.        
  38.         // atomic substraction
  39.         m2.lock();
  40.         k--;
  41.         if(k>0) obj.notify();
  42.         m2.unlock();
  43.         lock.unlock();
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement