Exercise 1 (Openmp-Ii) : Scenario - I
Exercise 1 (Openmp-Ii) : Scenario - I
Exercise 1 (OpenMP-II)
SCENARIO – I
Write a simple OpenMP program to employ a ‘reduction’ clause to express the reduction of a for
loop. In order to specify the reduction in OpenMP, we must provide
1. An operation (+ / * / o)
2. A reduction variable (sum / product / reduction). This variable holds the result of the
computation.
ALGORITHM:
Since the sum and product will be combined later, they will be in the reduction clause.
SOURCE CODE:
1. Sum:
#include <stdio.h>
#include <omp.h>
int main(void){
int arr[18] =
{10,20,30,90,40,50,70,60,80,100,110,120,130,140,150,160,170,180},
i, sum=0;
#pragma omp parallel shared(arr) reduction(+: sum)
{
#pragma omp for
for(i = 0; i < 18; i++){
sum += arr[i];
}
printf("Sum of elements are = %d\n", sum);
}
printf("Total Sum is = %d\n",sum);
}
2. Product:
#include <stdio.h>
#include <omp.h>
int main(void){
int arr[18] = {1,2,3,9,4,5,7,6,8,1,1,2,3,4,5,6,7,8}, i, prod=1;
#pragma omp parallel shared(arr) reduction(*: prod)
{
#pragma omp for
Reg No : 19BCE2028
Name : Pratham Shah
for(i = 0; i < 18; i++){
prod *= arr[i];
}
printf("Prod of elements are = %d\n", prod);
}
printf("Prod of all elements = %d\n",prod);
}
Sum:
Product:
RESULTS: a ‘reduction’ clause to express the reduction of a for loop was successfully
executed. The reduction clause specifies that one or more variables that are private to each
thread are the subject of a reduction operation at the end of the parallel region.
Reg No : 19BCE2028
Name : Pratham Shah
SCENARIO – II
Write a simple OpenMP program for performing the reduction of orphaned parallel loops.
Perform this operation for a dot product by printing the thread IDs and sum.
1. Start
2. The floats a, b are set to a predefined size of 10
3. All the elements of the float array a, b are initialized with values of
consecutive integers in float type and sum is initialized to float value 0
4. A function dotprod is defined in which
• tid = the thread number
• In the pragma loop, reduction clause using + as operation and sum
as reduction variable is specified. Dot product is calculated using
for loop and result is stored in sum
• For every iteration of the for loop, the thread ID is printed
5. In the main, a pragma parallel block is used to call the dotprod function
and Sum is printed
6. Stop
SOURCE CODE:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h> #define VECLEN
10 float a[VECLEN], b[VECLEN],
sum; float dotprod () {
int i,tid;
tid = omp_get_thread_num();
#pragma omp for reduction(+:sum)
for (i=0; i < VECLEN; i++)