/******* ** ** To compile for ** mc -sync mpc -arch mpi -o ps-new -m ps-new.m ** *******/ /********************************************************************** ** ** This is a parallel version of the sieve.m program. ** An END message is added to detect termination condition. ** The program terminates when the last sieve receives an END message. ** ** **********************************************************************/ /********************************************************************** ** ** Sieve of Eratosthenes ** ** This program implements the Sieve Of Eratosthenes algorithm to ** generate prime numbers from a sequence of consecutive natural ** numbers beginning with the smallest prime, 2. ** ** The entities used: ** (1) sieve: Each instance of sieve entity stands ** for a prime number. ** (2) driver: Initiate the program and generate the ** sequence of consecutive natural numbers. ** **********************************************************************/ #include "maisie.h" /********** ** ** SIEVE: The first message contains the prime number ** represented by the current instance of sieve entity. ** The entity creates another instance of sieve and then ** enters a loop. In the loop. the entity accepts all ** subsequent numbers from its creator and pass only ** those number not a multiple of its prime number. ** **********/ entity sieve{int myno} { message number { int number; } number; message end {} end; ename next_sieve; int myprime; wait until { mtype(number) myprime = msg.number.number; or mtype(end) terminate(); } print("Sieve number %d is for prime number %d", myno, myprime); next_sieve = new sieve{ myno+1 } at (myno/nnodes()); for(;;) wait until { mtype(number) /* A new number!! */ if(msg.number.number % myprime) /* Multiple of myprime? */ invoke next_sieve /* If not, pass to the */ with number = msg.number; /* next sieve entity. */ or mtype(end) invoke next_sieve with end; } } /********** ** ** DRIVER: Ask for how many natural numbers to generate, create the ** first sieve entity, and then generate the sequence of ** consecutive natural numbers and send to the first sieve. ** **********/ entity driver{int argc, char **argv} { int i, n; ename first; n = 300; if(argc > 1) n = atoi(argv[1]); first = new sieve{ 1 } ; for(i = 2 ; i <= n; ++i) { invoke first with number { i }; }; invoke first with end; }