#include #include #include #define THREADS 32 #define START 0 #define END 100000 /* the function called for each thread */ float sum_part() { /* get our thread id */ int id = omp_get_thread_num(); /* calculate the start and end points by evenly dividing the range */ unsigned long start = ((END - START) / THREADS) * id; unsigned long end = start + ((END - START) / THREADS) - 1; /* the last thread needs to do all remaining ones */ if (id == (THREADS - 1)) { end = END; } /* do the calculation */ unsigned long i; float sum = 0; for (i = start; i <= end; i++) { sum += i; } return sum; } int main() { float global_sum = 0; #pragma omp parallel num_threads(THREADS) reduction(+:global_sum) global_sum += sum_part(); /* now all results are in */ printf("Final answer = %f.\n", global_sum); return 0; }