Subversion Repositories programming

Rev

Rev 304 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*******************************************************************************
 * proj1-parallel.c - implement a simple program that will find the minimum
 *                    and maximum numbers out of a randomly generated list of
 *                    integers, using MPI to parallelize the operation.
 *
 * Copyright (c) 2006, Ira W. Snyder (devel@irasnyder.com)
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 ******************************************************************************/

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <mpi.h>

#define ROOT_NODE 0
#define TAG_MAX  0x1010
#define TAG_MIN  0x0101
#define TAG_SIZE 0x0808
#define TAG_DATA 0x0c0c

void find_max_and_min (const int *numbers, const int size, int *max, int *min)
{
    int i;
    *max = INT_MIN;
    *min = INT_MAX;

    for (i=0; i<size; i++)
    {
        if (numbers[i] > *max)
            *max = numbers[i];

        if (numbers[i] < *min)
            *min = numbers[i];
    }
}

void print_local_max_and_min (const int proc_id, const int max, const int min)
{
    printf ("Local max for process %d: %d\n", proc_id, max);
    printf ("Local min for process %d: %d\n", proc_id, min);
}

int main (int argc, char *argv[])
{
    int numprocs, myid, i;
    int n = -1;
    int c = -1;

    int size;
    int *numbers;

    int max = INT_MIN;
    int min = INT_MAX;

    int temp_max, temp_min;

    MPI_Status status;

    MPI_Init (&argc, &argv);
    MPI_Comm_size (MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank (MPI_COMM_WORLD, &myid);

    if (myid == ROOT_NODE)
    {
        /* Parse the command line options */
        opterr = 0;

        while ((c = getopt (argc, argv, "n:")) != -1)
        {
            switch (c)
            {
                /* Try to get -n option */
                case 'n':
                    n = atoi (optarg);
                    break;

                /* Catch bad options */
                case '?':
                    if (isprint (optopt))
                        fprintf (stderr, "Unknown option '-%c'.\n", optopt);
                    else
                        fprintf (stderr, "Unknown option character '\\x%x'.\n", optopt);

                    return 1;
                    break;
                default:
                    abort ();
            }
        }

        /* Check if the n value is valid */
        if (n<=0)
        {
            fprintf (stderr, "Bad value for n, must be greater than 0\n");
            fprintf (stderr, "Please specify the '-n NUMBER' option\n");
            return 1;
        }

        /* Make sure that we have the ability to calculate the answer */
        if (n % numprocs != 0)
        {
            fprintf (stderr, "n must be evenly divisble by numprocs\n");
            fprintf (stderr, "Please adjust -n and -np adequately\n");
            return 2;
        }

        /* Allocate memory for the random number array */
        if ((numbers = (int*) malloc (n * sizeof(int))) == NULL)
        {
            puts ("Out of memory");
            return 1;
        }

        /* Seed the random number generator */
        srand (time(NULL));

        /* Generate random numbers, staying in the range [0,10n) */
        for (i=0; i<n; i++)
            numbers[i] = (int) ((n*10.0) * rand() / (RAND_MAX + 1.0));

        /* Calculate slice size */
        size = n/numprocs;

        /* Send out n to everyone */
        for (i=1; i<numprocs; i++)
            MPI_Send (&size, 1, MPI_INT, i, TAG_SIZE, MPI_COMM_WORLD);

        /* Send out data to everyone */
        for (i=1; i<numprocs; i++)
            MPI_Send (numbers+(size*i), size, MPI_INT, i, TAG_DATA, MPI_COMM_WORLD);

        /* Print some information */
        printf ("Size of the List: %d\n", n);
        printf ("No. of processes: %d\n\n", numprocs);

        /* Calculate my part of the data */
        find_max_and_min (numbers, size, &max, &min);

        print_local_max_and_min (myid, max, min);

        /* Recieve data back */
        for (i=1; i<numprocs; i++)
        {
            /* Find actual max */
            MPI_Recv (&temp_max, 1, MPI_INT, i, TAG_MAX, MPI_COMM_WORLD, &status);
            
            if (temp_max > max)
                max = temp_max;

            /* Find actual min */
            MPI_Recv (&temp_min, 1, MPI_INT, i, TAG_MIN, MPI_COMM_WORLD, &status);

            if (temp_min < min)
                min = temp_min;

            print_local_max_and_min (i, temp_max, temp_min);
        }

        printf ("\nOverall max: %d\n", max);
        printf ("Overall min: %d\n", min);
    }
    else // not ROOT_NODE
    {
        /* Recieve size of the data */
        MPI_Recv (&size, 1, MPI_INT, ROOT_NODE, TAG_SIZE, MPI_COMM_WORLD, &status);

        /* Allocate memory to store the data */
        if ((numbers = (int*) malloc (size * sizeof(int))) == NULL)
        {
            puts ("Out of memory");
            return 1;
        }

        /* Recieve the data */
        MPI_Recv (numbers, size, MPI_INT, ROOT_NODE, TAG_DATA, MPI_COMM_WORLD, &status);

        /* Calculate the max and min of my part of the data */
        find_max_and_min (numbers, size, &max, &min);

        /* Send the max and min back to the root node */
        MPI_Send (&max, 1, MPI_INT, ROOT_NODE, TAG_MAX, MPI_COMM_WORLD);
        MPI_Send (&min, 1, MPI_INT, ROOT_NODE, TAG_MIN, MPI_COMM_WORLD);
    }

    free (numbers);
    MPI_Finalize ();

    return 0;
}