Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following code uses OpenMP. #include <iostream> #include <omp.h> using names

ID: 3674739 • Letter: T

Question

The   following   code   uses   OpenMP.
#include   <iostream>
#include   <omp.h>
using   namespace   std;
int   main()
{
int   i;
#pragma   omp   parallel   for  
for   (i=0;   i<10;   i++)
cout<<i<<endl;
cin.get();
return   0;
}
However,   it   may   print   two   or   more   digits in   the   same   line   like   the   following   case.
5
6
9
36
3
6
9
1
4
Please   update   the   code   to   avoid   this   problem   and   still   use   OpenMP for  
parallel   computing. You   may   want   to   consider   to   use   #pragma   omp   critical

Explanation / Answer

Answers:)

As #pragma   omp   parallel   for is used for for loop, multiple threads will be created to execute the for loop but this does not guarantee that each thread will be synchronized. For example, suppose one thread is at the moment performing output operation and printing on console, there is another thread which has got the updated value of 'i' and is also performing output operation and prints on console, this will appear like both the threads wrote on the same line, that's why we get two or more digits on the same line even though "endl" key is mentioned.

Updated code to avoid the problem:

#include   <iostream>
#include   <omp.h>
using   namespace   std;
int   main()
{
int   i;
#pragma   omp   parallel   for  
for   (i=0;   i<10;   i++)

{

#pragma   omp   critical (lock1)
cout<<i<<endl;

}
cin.get();
return   0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote