CS 220 Parallel Computing

sleep_sort.c

DownloadView Raw

/**
 * sleep_sort.c
 *
 * Sorts a random collection of values using sleep()
 *
 * Compile:  mpicc -g -Wall -lm sleep_sort.c -o sleep_sort
 *           (or run make)
 *
 * Run:      mpirun -n 4 ./sleep_sort
 */

#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

const int MAX_CONTRIB = 10;

void sort(int my_contrib, int my_rank);

int main(int argc, char* argv[]) {
    int p, my_rank;
    MPI_Comm comm;
    int my_contrib;
    int sum;

    MPI_Init(&argc, &argv);
    comm = MPI_COMM_WORLD;
    MPI_Comm_size(comm, &p);
    MPI_Comm_rank(comm, &my_rank);

    if (my_rank == 0) {
        printf("Generating random values...\n");
    }

    srandom(my_rank + 1 + 25);
    my_contrib = random() % MAX_CONTRIB;
    printf("Proc %d > my_contrib = %d\n", my_rank, my_contrib);
    fflush(stdout);

    if (my_rank == 0) {
        printf("[Press enter to start.]\n");
        getchar();
        printf("Sorting values...\n");
        fflush(stdout);
    }

    MPI_Barrier(comm);

    sort(my_contrib, my_rank);

    MPI_Finalize();
    return 0;
}

/**
 * Function:    sort
 * Purpose:     Sleeps for a given amount of time, and then prints the process
 *              contribution (random number).
 *
 * Input args:  my_contrib  the number to help sort
 *              my_rank     rank of the process
 */
void sort(int my_contrib, int my_rank) {
    sleep(my_contrib);
    printf("Proc %d > my_contrib = %d\n", my_rank, my_contrib);
}