0

I am writing a multithread Java program that simulates game of life. There is one thread for each cell computing the next value for cell aliveness value. I solved %95 of the problem threads working correctly and synchronized but I can't figure out how to print out cell matrix after each step. I have the following run method in my threads:

public void run(){
  while(true){ //this may also be finite
    calculateNeighbourCount(); //threads count their alive neighbours
    calculateBarrier(); //Threads wait until all threads complete calculation before changing content
    next();//threads make cell's value the next computed value.
    nextBarrier(); //Threads wait until all threads complete next()
    //Here I want to print out cell matrix
  }
}

One possible solution I can think of is to allocate memory considering number of iterations.For example if i have mxn cell matrix and k number of iterations I need mxnxk 3d array. Then I store outputs with proper indexes in this array and output after execution.But this solution seems very bad due to the memory usage. I need a workaround to print the snapshot of the matrix when all cells changed together.

Jivings
  • 22,834
  • 6
  • 60
  • 101
woryzower
  • 956
  • 3
  • 15
  • 22
  • so are you talking the matrix is shared belong to all threads? and are you trying to show it in a [thread-safe](http://arashmd.blogspot.com/2013/06/java-threading.html#synctr) manner? –  Oct 20 '13 at 11:45

1 Answers1

1

From the java documentation:

A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

You can see an example in the docs here, but generally, one of the constructors accepts a Runnable. You can use that to do your printing after each cycle.

Kraylog
  • 7,383
  • 1
  • 24
  • 35
  • I am using this custom barrier http://stackoverflow.com/questions/6331301/implementing-an-n-process-barrier-using-semaphores – woryzower Oct 20 '13 at 12:57