/********************************************************** File: slave.cc Description: A program that inputs an integer number and determines if it is a prime number or not in parallel. Functions for the slave processes. Author: Dana Vrajitoru Organization: IUSB Date: September 28, 2004 ***********************************************************/ #include #include #include "slave.h" // The slave function that checks if n is prime. While in the loop for // testing the potential divisors, it also checks if the master has // any information about the loop having to end, which means that some // other process has found a non-trivial divisor in the meantime. void Check_prime_slave(int start, int end, int n) { MPI_Request request; MPI_Status status; int flag = 0, div=1, divisor = 1; MPI_Irecv(&div, 1, MPI_INT, MASTER_ID, 0, MPI_COMM_WORLD, &request); for (int i=start; i<=end && divisor == 1; i += 2) { if (n % i == 0) divisor = i; MPI_Test(&request, &flag, &status); if (flag) divisor = div; } MPI_Send(&divisor, 1, MPI_INT, MASTER_ID, 0, MPI_COMM_WORLD); if (!flag) MPI_Wait(&request, &status); } // The slave function. It waits for the master to communicate the // number to be checked, sets the limits of search for itself, then // calls the function that checks if the number is prime. void Slave(int proc_id, int nr_proc) { int n; MPI_Bcast(&n, 1, MPI_INT, MASTER_ID, MPI_COMM_WORLD); if (n % 2 != 0) { int sqroot = sqrt(n), found_div = 0; int steps = (sqroot - 2)/nr_proc; int start = 3 + steps * proc_id, end = start + steps-1; if (start % 2 == 0) start++; if (proc_id == nr_proc -1) end = sqroot; Check_prime_slave(start, end, n); } }