Search code examples
cparallel-processingopenmp

parallel program in c using openmp is not working correctly


when I run this code in code blocks it gives a strange output

#include<omp.h>
#include<stdio.h>
int main (int argc, char* argv[])
 {

int id, var2=2, var3 =3;

/* sequential code */
printf("I am a serial region. \n");

#pragma omp parallel private(var2) shared(var3)
{
    id = omp_get_thread_num();
    if(id == 0){
        var2 = 22;
    }
    printf ("hello from thread %d\n" , id);
    printf("var2 %d \n " , var2);
    printf("var3 %d \n " , var3);
}

/* sequential code */
printf("I am a serial region. \n");
}

so, why the output is not organized ?

output


Solution

  • I'm assuming you are talking about the messed up lines rather than things out of order. You can't expect parallel printing in any order. That's just the nature of doing things in parallel.

    If you are referring to the line that goes hello from threadhello from thread 1 and the weird v 0, what you are probably dealing with is a data race. Any variable outside of a work region, is by default shared. You didn't explicitly declare id as private or shared so it is automatically shared between threads. You may be accessing and writing the value of id at the same time between threads. Anytime you have a data race, the behavior is undefined so you could see all sorts of weird things. To fix, you will need to specify it as private or just declare id in the for loop.