if (myrank == 0)
{
// read from file
...
// send target value to all other processes
for (i = 1; i < nrprocs; i++)
{
MPI_Send (&target, 1, MPI_INT, i, TAG1, MPI_COMM_WORLD);
}
// calculate len
len = n / nrprocs;
// send len to all other processes
for (i = 1; i < nrprocs; i++)
{
MPI_Send (&len, 1, MPI_INT, i, TAG2, MPI_COMM_WORLD);
}
// send to each process a part of the array to be searched
for (i = 1; i < nrprocs; i++)
{
MPI_Send (&b[(i-1)*len], len, MPI_INT, i, TAG3, MPI_COMM_WORLD);
}
// the root process searches the last portion
for (i = ((nrprocs - 1)*len); i < n; i++)
{
if (b[i] == target)
printf ("%d ", i);
}
no = 0;
while ( no != (nrprocs - 1) )
{
MPI_Recv (&index, 1, MPI_INT, 1, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
if (status.MPI_TAG == END_TAG)
{
no++;
}
else
{
printf ("%d ", index);
}
}
}
else
{
MPI_Recv (&target, 1, MPI_INT, 0, TAG1, MPI_COMM_WORLD, &status);
MPI_Recv (&len, 1, MPI_INT, 0, TAG2, MPI_COMM_WORLD, &status);
MPI_Recv (&b[0], len, MPI_INT, 0, TAG3, MPI_COMM_WORLD, &status);
index = -1;
for (i = 0; i < len; i++)
{
if (b[i] == target)
{
index = (myrank - 1)*len + i;
MPI_Send (&index, 1, MPI_INT, 0, TAG, MPI_COMM_WORLD);
}
}
// message saying that the current process has finished searching
MPI_Send (&index, 1, MPI_INT, 0, END_TAG, MPI_COMM_WORLD);
}