0% found this document useful (0 votes)
30 views3 pages

PDC Lab 4

The document discusses two programs that use critical sections in OpenMP. The first program divides numbers across two threads and finds the minimum local sum. The second program calculates Taylor's expansion using four threads and outputs the final result in a critical section.

Uploaded by

Aliza Azhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views3 pages

PDC Lab 4

The document discusses two programs that use critical sections in OpenMP. The first program divides numbers across two threads and finds the minimum local sum. The second program calculates Taylor's expansion using four threads and outputs the final result in a critical section.

Uploaded by

Aliza Azhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

LAB NO: 04

Critical Section
Objective
Implement the concept of Critical Section in OpenMP.

LAB EXERCISE:
Program 1: Write a program that divides 20 numbers on 2 threads. Find local sum on each
thread. Find which thread has minimum local sum.

OpenMP Code:
#include<stdio.h>
#include<omp.h>
main(){
int tid,i,sum=0,min;
int a[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
#pragma omp parallel private(tid,sum)
{
sum=0;
tid=omp_get_thread_num();
if(tid==0){
for(i=0;i<10;i++){
sum=sum+a[i];
}
printf("Sum of 1st thread is = %d\n",sum);
}
else
{
if (tid == 0) {
min = sum;
}
for(i=10;i<20;i++){
sum=sum+a[i];
}
printf("Sum of 2nd thread is = %d\n",sum);
}
#pragma omp critical
{
if(sum<min){
min=sum;
}
}
}
printf("Minimum number is %d\n",min);
}
Output:

Program 2: Write a program that solve Taylors Expansion using 4 threads. Use critical section
for final output.
OpenMP Code:
#include <stdio.h>
#include <omp.h>
Int main() {
Int n = 10;
Double x = 1.0;
Double sum = 0.0;
Int I;
#pragma omp parallel for num_threads(4) reduction(+:sum)
For (I = 0; I < n; i++) {
Double term = 1.0;
Int j;
For (j = 1; j <= I; j++) {
Term *= x / j;
}
Sum += term;
}
#pragma omp critical
Printf(“The result of Taylor’s expansion is %f\n”, sum);
Return 0;
}
Output:

You might also like