Untitled
unknown
c_cpp
a year ago
2.6 kB
6
Indexable
int main(int argc, char **argv) { int myrank, nprocs; int *A; // the input array int *my_A; // subarray of A int N; // size of the input array MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); if (myrank == 0) { A = (int *) malloc(sizeof(int)*N); // We assume A and N are initialized here } /* The root process first broadcasts chunkSize, the size of the subarray of A each process will check. This enables the processes to allocate memory for the subarray. And then the root scatters the array itself. */ int chunkSize; if (myrank == 0) chunkSize = N/nprocs; // we assume remainder is 0 MPI_Bcast(&chunkSize, 1, MPI_INT, 0, MPI_COMM_WORLD); my_A = (int *) malloc(sizeof(int)*chunkSize); MPI_Scatter(A, chunkSize, MPI_INT, my_A, chunkSize, MPI_INT, 0, MPI_COMM_WORLD); int counters[2]; /* counters[0] is the positive count, counters[1] is the negative count */ count(my_A, chunkSize, &counters[0], &counters[1]); int global_counters[2]; // used by process 0 MPI_Reduce(counters, global_counters, 2, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (myrank == 0) { /* Each of the worker processes could not check the first element in its chunk because the previous element was not available. Now process 0 completes the work: Iterate over chunks. if the previous chunk ends in 10, check if f() applied to the first element of the current chunk is positive or negative and then update the appropriate counter */ for (int start_index = chunkSize; start_index < N; start_index += chunkSize) { int last_element_in_previous_chunk = A[start_index-1]; if (last_element_in_previous_chunk == 10) { int r = f(A[start_index]); if (r > 0) global_counters[0]++; else if (r < 0) global_counters[1]++; } } /* for */ if (global_counters[0] > global_counters[1]) printf("positive\n"); else if (global_counters[0] < global_counters[1]) printf("negative\n"); else printf("equal\n"); printf("counter positive=%d, counter negative=%d\n", global_counters[0], global_counters[1]); } // myrank == 0 MPI_Finalize(); return 0; } void count(int *array, unsigned int size, int *count_positive, int *count_negative){ int positive = 0, negative = 0; #pragma omp parallel for default(none) shared(array, size) reduction(+:positive,negative) for (int i = 1; i < size; i++) if (array[i-1] == 10) { int r = f(array[i]); if (r > 0) positive++; else if (r < 0) negative++; } *count_positive = positive; *count_negative = negative; }
Editor is loading...
Leave a Comment