Professional Documents
Culture Documents
Exercise 2 (OpenMP-II)
SCENARIO – I
Combined parallel loop reduction
Algorithm:
1. Start
2. Read variables i, n and sum.
3. Read arrays a and b.
4. Initialize n<-100.
5. Initialize the arrays inside a for loop.
6. Initialize sum=0.
7. Start the parallel loop and store the value of parallel executions into the variable
sum.
NOTE: #pragma omp parallel for turns the loop into a parallel loop. The
reduction(+:sum) declares that we’re reducing the input array by summing into the
variable sum, so after the partial loops are done, teir results are summed into this
variable.
8. Display sum.
9. Stop.
Reg No: 17BCE0500
Name: Rahul Mangal
Lab Slot: L25+L26
Source Code:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
Output Screenshot:
Result:
17bce0500@sjt418scs019:~/Desktop$ gcc -o Combined_parallel_loop_reduction
-fopenmp Combined_parallel_loop_reduction.c
17bce0500@sjt418scs019:~/Desktop$ ./ Combined_parallel_loop_reduction
Sum = 328350.000000
Reg No: 17BCE0500
Name: Rahul Mangal
Lab Slot: L25+L26
SCENARIO – II
Orphaned Parallel loop reduction
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.
Algorithm:
1. Start
2. Define vector length as VECLEN=10.
3. Declare array a,b and sum.
4. Start function dotproduct()
4.1. Declare variables i and tid.
4.2. use function omp_get_thread_num() to get the thread number.
4.3. Start the parallel loop and store the value of parallel executions into the
variable sum.
NOTE: #pragma omp parallel for turns the loop into a parallel loop. The
reduction(+:sum) declares that we’re reducing the input array by summing into the
variable sum, so after the partial loops are done, teir results are summed into this
variable.
5. Start the parallel loop and store the value of parallel executions into the variable
sum.
6. Display the thread id for each value of counter variable i.
7. Start the main function
7.1. Read variable i.
7.2. Initialize array a and b.
Reg No: 17BCE0500
Name: Rahul Mangal
Lab Slot: L25+L26
Source Code:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define VECLEN 10
float dotprod ()
{
int i,tid;
tid = omp_get_thread_num();
#pragma omp for reduction(+:sum)
for (i=0; i < VECLEN; i++)
{
sum = sum + (a[i]*b[i]);
printf(" tid= %d i=%d\n",tid,i);
}
}
printf("Sum = %f\n",sum);
Output Screenshot:
Result:
17bce0500@sjt418scs008:~/Desktop$ gcc -o orphaned_parallel_loop_reduction
-fopenmp orphaned_parallel_loop_reduction.c
17bce0500@sjt418scs008:~/Desktop$ ./ orphaned_parallel_loop_reduction
tid= 0 i=0
tid= 2 i=6
tid= 2 i=7
tid= 0 i=1
Reg No: 17BCE0500
Name: Rahul Mangal
Lab Slot: L25+L26
tid= 0 i=2
tid= 3 i=8
tid= 3 i=9
tid= 1 i=3
tid= 1 i=4
tid= 1 i=5
Sum = 285.000000