i want write program computes factorial of integer, using parallel computation (open mp library).
clearly program below suffers race condition.
// each loop iteration writes value different iteration reads. #pragma omp parallel for (i=2; < 10; i++) { factorial[i] = * factorial[i-1]; }
i read somewhere pow , factorial calculations can in no way done parallely, true or above program (in c, using openmp library) can modified calculate factorial paralelley ?
thanks.
you can in parallel running on array twice. first time calculate partial products , save total partial product per thread. in second pass correct each element total product previous thread. similar how cumulative sum (aka prefix sum) in parallel except it's cumulative product in parallel.
#include <stdio.h> #include <stdlib.h> #include <omp.h> int main(void) { int n = 10; int factorial[n]; factorial[1] = 1; int *proda; #pragma omp parallel { int ithread = omp_get_thread_num(); int nthreads = omp_get_num_threads(); #pragma omp single { proda = malloc(nthreads * sizeof *proda); proda[0] = 1; } int prod = 1; #pragma omp schedule(static) nowait (int i=2; i<n; i++) { prod *= i; factorial[i] = prod; } proda[ithread+1] = prod; #pragma omp barrier int offset = 1; for(int i=0; i<(ithread+1); i++) offset *= proda[i]; #pragma omp schedule(static) for(int i=1; i<n; i++) factorial[i] *= offset; } free(proda); for(int i=1; i<n; i++) printf("%d\n", factorial[i]); putchar('\n'); }
Comments
Post a Comment