Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mutex.Lock;
- import mutex.Mutex;
- public class Test{
- public static void main(String args[]){
- new Test().process();
- }
- void process(){
- int size = 100;
- Lock lock = new Mutex(size);
- inc(size, lock);
- }
- void inc(int np, Lock lock){
- MyThread t[] = new MyThread[np];
- for(int i=0;i<np;i++){
- t[i] = new MyThread(i, lock);
- t[i].start();
- int v = t[i].getCountValue();
- System.out.println("count value:t["+i+"]"+v+" "+(i==v?"":"XXX"));
- }
- }
- }
- import mutex.Lock;
- import mutex.Mutex;
- public class MyThread extends Thread{
- private int pid;
- private Lock lock;
- private static int count = 0;
- public MyThread(int pid, Lock lock){
- this.pid = pid;
- this.lock = lock;
- }
- public void run(){
- this.lock.lock(this.pid);
- increament();
- //decreament();
- this.lock.unlock(this.pid);
- }
- public void increament(){
- count++;
- }
- public void decreament(){
- count--;
- }
- public int getCountValue(){
- return this.count;
- }
- }
- package mutex;
- public interface Lock{
- void lock(int pid);
- void unlock(int pid);
- }
- package mutex;
- public class Mutex implements Lock{
- int N;
- boolean takeANumber[];
- int valueOfProcess[];
- public Mutex(int n){
- this.N = n;
- takeANumber = new boolean[N];
- valueOfProcess = new int[N];
- for(int i=0;i<N;i++){
- takeANumber[i] = false;
- valueOfProcess[i] = 0;
- }
- }
- public void lock(int pid){
- // 1. take a number
- takeANumber[pid] = true;
- for(int i=0;i<N;i++){
- if(valueOfProcess[i]>valueOfProcess[pid]){
- valueOfProcess[pid] = valueOfProcess[i];
- }
- }
- valueOfProcess[pid]++; // line up
- takeANumber[pid] = false;
- // 2. check whose number is the smallest
- for(int i=0;i<N;i++){
- while(takeANumber[i]); // if other processes are taking a number, wait for them finishing that procedure.
- while((valueOfProcess[i]!=0 &&
- ((valueOfProcess[i]<valueOfProcess[pid])||
- (valueOfProcess[i]==valueOfProcess[pid]&&i<pid)))); // busy wait
- }
- }
- public void unlock(int pid){
- valueOfProcess[pid] = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement