/* PSORT (P(arallel)SORT) Jim Garlick The purpose of this program is to sort a list of numbers in parallel and then find the median in the list. The program is divided into two sections: parent and child. The parent is in charge of reading in the numbers, starting the first layer of children, and outputting the resulting median. The children receive from the parent and spawn some children of their own and then receive those responses. The program can be thought of as being recursive: the parent creates a child copy of itself, which in turn creates its own children. */ #include #include #include "pvm3.h" #include "mergesort.h" #define BINNAME "psort" #define TO_MASTER 1 #define TO_SLAVE 2 void process(float *array, int n, int level); void sendToChild (int level, int length, float *array); void copyArray(float *to, float *from, int n); int main (int argc, char* argv[]) { char filename[256], tmp[100]; FILE *input, *output; int i; /* Pointer that will contain the entire data set array */ float *mainData, median; int n, level; /* get the parent's id (if there is one) */ int parent_id = pvm_parent(); /* If there is no parent */ if (parent_id == PvmNoParent) { /* Get info from command line */ if (argc < 3) { printf("usage: %s []\n", BINNAME); exit(1); } level = atoi(argv[1]); strcpy(filename, argv[2]); /* Open the file for reading */ if ((input = fopen(filename, "r")) == NULL) { fprintf(stderr, "Error opening %s\n", filename); exit(1); } /* Count the number of numbers in the file */ for(n=0; fgets(tmp, sizeof(tmp), input); n++); rewind(input); printf("Sorting %d numbers.\n", n); /* Allocate memory for the array */ mainData = (float*)malloc(n * sizeof(float)); /* Read in the numbers */ for(i=0; fgets(tmp, sizeof(tmp), input); i++) sscanf(tmp, "%f", &mainData[i]); fclose(input); /* Sort n elements of mainData splitting it level times */ process(mainData, n, level); /* Save the sorted data to a file if it's given */ if (argc == 4) { output = fopen(argv[3], "w"); printf("Saving sorted data to %s\n", argv[3]); for (i=0; i=0 && n>5); i--, numSpawned++) { /* Split the array */ newN = (n/2); printf("Level: %d :: ", i); printf("Keeping %d, Sending %d\n", newN, (n-newN)); /* Send to the child, the level, the length of the new array and the second half of the array */ sendToChild(i, (n-newN), &whole[newN]); n = newN; } printf("Lowest level reached with %d spawned.\n",numSpawned); /* Then we process what's left over */ printf("Sorting %d remaining elements.\n", n); quicksort(whole, 0, n); /* Now we start receiving from the children... */ for (i=0; i