2016-09-28 1 views
-2

Я работаю над этим кодом в течение нескольких дней. И я пытаюсь выяснить, в чем проблема. Я реализую семафоры и как они выбирают между процессами чтения и записи, для этого случая более важными являются процессы чтения mu и, следовательно, имеют более высокий приоритет. И я думаю, что мой класс Semaphore дает проблему, а не основной метод. Исключение составляет строка 29 в классе Семафор, которая имеет этот код for (int i = 0; i < updatedProcessArray.length; i++) Java Null PointerException. Пытается реализовать семафоры

У меня есть случайные 0 и 1, 0 - это процессы чтения, а 1 - процессы записи. Усвоение в моей программе состоит в том, что все процессы происходят одновременно и потому, что читатели 0 всегда имеют больше приоритета, они всегда будут обрабатываться первыми. Когда процессы завершены, -1 будет отмечать их индекс массива. Программа проходит через массив до тех пор, пока каждая вещь в массиве не станет отрицательной -1, что и было целью.

Семафор класс

class Semaphore 
{ 
    public int [] updatedProcessArray; // initializing array for update 
    public int readcount = 0; // keep track of sharedData process 

    public int signal; // process signal on 00 for reader, on for 01 writer, 10 wait for reader, 11 wait for writer. 
    //public int priortyReader = 0; // priorty check for readers, with 1 being priorty 
    public int processesCompleted = 0; 


    //Semaphore constructor 
    Semaphore(int[] processArray) 
    { 
     int[] updatedProcessArray = processArray.clone(); // copy array  
    } 

    public int signalQueue(int muxtex, int wrt, int index) 
    { 
     int mu = muxtex; // assgining all process semaphore 
     int wr = wrt; // assigning writer semahpore 
     int currentIndex = index; // index for current process 
     int priorityIndex = 0; // index for priority 
     int priorityReader = 0; 
     int minimumWriterIndex = 0; // index of lowest writer (writer with the highest priority) 

     //int array[]; 
     // loop through array 
     for (int i = 0; i < updatedProcessArray.length; i++) 
     { 
      // Checking the top priority in the queue 

      //independent if statement 
      if (wr == updatedProcessArray[i] && currentIndex == i) 
      { 
       if (minimumWriterIndex != 1) 
        minimumWriterIndex = 1; // record first index with writer 
      } 

      if (mu == updatedProcessArray[i] && currentIndex == i) 
      { 
       //priorityIndex = 0; 
       //signal = 00; // the priority has been found, reader. 


       // As soon as the first priority is found reader priorty is found, 
       // there is no greater priorty in the queue 
       //priorityReader = 1; // all reader processes have priority over writer processes 
       //priorityIndex = i; // recording the priority index 
       return (updatedProcessArray[i] = -1); // marking off to show that job being processed. 


      } 
      else 
      { 
       if (mu == updatedProcessArray[i]) 
        // keeping track of readers 
        priorityReader = 1; // to show all reader processes have priority over writer processes 

      }  
     } 

     if (priorityReader != 1 && minimumWriterIndex == 1) 
      return (updatedProcessArray[minimumWriterIndex] = -1); 

     return 0;    
    } 

    public int waitQueue(int mutex, int wrt, int index) 
    { 
     // declaring variables 
     int mu = mutex; 
     int wr = wrt; 
     int currentIndex = index; 

     if (readcount < 1) 
     { 
      // comparing current index value with semaphore mutex 
      if (mu == updatedProcessArray[currentIndex]) 
      { 
       signal = 10; 
       return signal; //reader process waiting 
      } 
      // comparing current index value with semaphore wrt 
      if (wr == updatedProcessArray[currentIndex]) 
      { 
       signal = 11; //writer process waiting 
       return signal; 
      } 
      return 0; 
     } 
     return 0; 
    } 
    // for our purpose Signal method will be used for wait as well 
    public int signal() 
    { 
     if (signal == 00 || signal == 01) 
     { 
      readcount++; 
     return signal; 
     } 


     if (signal == 10 || signal == 11) 
     { 
      readcount--; 
      return signal; 
     } 
     return 0; 
    } 
    public int getProcessesCompleted() 
    { 
     int sum = 0; 
     for (int i = 0; i < updatedProcessArray.length; i++) 
     { 
     if (updatedProcessArray[i] == -1) 
      sum++; // update sum 
     } 
     return sum; 
    } 
    public int[] updateArray() 
    { 
     return updatedProcessArray; 
    } 
} 

Основной метод

import java.util.Random; 

    class SemaphoreTest 
    { 
     public static void main(String args[]) 
     { 
      Random rn = new Random(); // creating a new random object 

      int processArraySize = rn.nextInt(11); // size of processArray 

      int[] processArray = new int[processArraySize]; // giving array size 

      int mutex = 0; // semaphore for readers 
      int wrt = 1; // semaphore for writers 

      // Now we will initialize populate processArray 
      for (int i = 0; i < processArraySize; i++) 
      { 
       int x = rn.nextInt(2); // we will denote 0 as reader and 1 as writer 
       processArray[i] = x; // assigning x to index i 

      } 

      Semaphore semaphore = new Semaphore(processArray); // creating a new semaphore object 
      int signal = 0; 

      int processCompleted = 0; 
      while(processCompleted < processArraySize) 
      { 
       // return the new and updated processArray each time 
       // a -1 will be where the processes have been completed 
       // the process will continue untill all process have been completed only -1's in the array 


       for (int i = 0; i < processArraySize; i++) 
       { 


        semaphore.signalQueue(mutex, wrt, i); // calling mutex semaphore and wrt semaphore 
       signal = semaphore.signal(); 
       if (signal == 00) 
       { 
        System.out.println("reader: using shared data \t index: " + i 
         + "number of processe(s) completed: " + semaphore.getProcessesCompleted()); 
       } 
       if (signal == 01) 
       { 
        System.out.println("writer: using shared data \t index: " + i 
         + "\tnumber of processe(s) completed: " + semaphore.getProcessesCompleted()); 
       } 
       // wait semaphore 
        semaphore.waitQueue(mutex, wrt, i); // calling mutex semaphore and wrt semaphore 
       if (signal == 10) 
       { 
        System.out.println("reader: waiting to access shared data \t index: " + i 
         + "number of processe(s) completed: " + semaphore.getProcessesCompleted()); 
       } 
       if (signal == 10) 
       { 
        System.out.println("writer: waiting to access shared data \t index: " + i 
         + "number of processe(s) completed: " + semaphore.getProcessesCompleted()); 
       } 
       }//end of for loop 

      // updating process completed 
      processCompleted = semaphore.getProcessesCompleted(); 

      }//end of while loop 

     }//end of method 
    } 
+3

Во-первых, пожалуйста, предоставьте MCVE (http://stackoverflow.com/help/mcve). Ключевое слово минимальное. Не вставляйте весь код, дайте нам МАЛЕНЬКИЙ возможный вариант вашего кода, который все еще воспроизводит проблему. И, во-вторых, если вы хотите, чтобы мы отлаживали исключение, по крайней мере, говорим, в какой строке оно происходит. – nhouser9

+0

Простите, что такое MVCE? где я должен поместить свой код? Исключение составляет строка 29 – Jam1

+0

Если вы хотите узнать, что такое MVCE, нажмите ссылку в моем исходном сообщении. – nhouser9

ответ

1

в конструкторе Семафор, Вы должны обратиться к атрибуту класса с ключевым словом это не должно создать новый массив, как вы работаете с массивом updatedProcessArray

изменение

Semaphore(int[] processArray) 
    { 
     int[] updatedProcessArray = processArray.clone(); // copy array  
    } 

в

Semaphore(int[] processArray) 
    { 
     this.updatedProcessArray = processArray.clone(); // copy array  
    } 

дополнительная рекомендация может использовать структуру переключателя, чтобы избежать многих, если

 switch(signal) 
      { 
       case 00: System.out.println("reader: using shared data \t index: " + i 
        + "number of processe(s) completed: " + semaphore.getProcessesCompleted());break; 
       case 01:instruction;break; 
       case 02: instruction;break; 
       default: not option 
      } 
+0

Я попробую оператор switch, спасибо. – Jam1

+0

Я мог бы отметить свой ответ, если я исправлю ваши неудобства. – DarkFenix

+0

Привет, извините, я собирался вас раздобыть! он компилируется и работает, просто исправляя несколько вещей, чтобы он мог работать как следует. 'This.updatedProcessArray' действительно помог. – Jam1

Смежные вопросы