[Shootout-list] process creation & message passing

Isaac Gouy igouy2@yahoo.com
Sat, 16 Oct 2004 14:48:20 -0700 (PDT)


chainmsg 
- create 3000 *linked* processes/threads/... 
- send message 0 from one end of the chain
- each process/thread/... receives an integer x, stores x, 
and passes x+1 to the next process/thread/... in the chain
: print the final sum (which should be 3000 * messages)
(1 parameter: how many messages are sent)

Timing within a Java 'chainmsg' program, gave
java chainmsg  200 -  11.266s
java chainmsg  400 -  20.219s
java chainmsg  600 -  29.218s
java chainmsg  800 -  38.688s
java chainmsg 1000 -  47.407s

That final test made 3,000,000 transfers.

public class chainmsg {
   static final int LENGTH = 3000;

   public static void main(String args[]) {
      int m = 1;
      if (args.length > 0) m = Integer.parseInt(args[0]);

      EndLink chainEnd = new EndLink(null, LENGTH * m);
      chainEnd.start();
      Link chain = chainEnd;
         
      for (int i=2; i<=LENGTH; i++){
         Link link = new Link(chain);             
         link.start();
         chain = link;
      }

      for (int i=0; i<m; i++) chain.put(0);  
   
      try { chainEnd.join(); } catch (InterruptedException e){} 
      System.out.println(chainEnd.checksum);
      System.exit(0);
   }
}


class Link extends Thread {
   Link next;
   int message = -1;
   boolean busy = false;
   
   Link(Link t){
      next = t;
   }

   public void run() { 
      for (;;) next.put(this.take());          
   }

   synchronized void put(int m) {
      while (busy)
         try { wait(); } catch (InterruptedException e){}   
      busy = true;
      message = m;
      notifyAll();

      while (message != -1)
         try { wait(); } catch (InterruptedException e){}  
      busy = false;
      notifyAll();            
   }

   synchronized int take() {
      while (message == -1)
         try { wait(); } catch (InterruptedException e){}  

      int m = message;
      message = -1;
      notifyAll();
      return m+1;             
   }
}


class EndLink extends Link {
   public long checksum = 0;
   private long finalsum;
   
   EndLink(Link t, int i){
      super(t);
      finalsum = i;
   }

   public void run() { 
      do 
         checksum += this.take(); 
      while (checksum < finalsum);       
   }
}



	
		
__________________________________
Do you Yahoo!?
Yahoo! Mail - You care about security. So do we.
http://promotions.yahoo.com/new_mail