Question

Hi all I am learning openMP. I did a self practice using this sample code. Now, I am confused with the output.

#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "math.h"

main ()  {

int tid;

int y, z;
int x=0;
int i;

#pragma omp parallel private(tid,i) shared(x,y,z) num_threads(2)
{
    tid = omp_get_thread_num();

    y = 25;
    if(tid==0)
    {
        y = 10;
    }
    else{ z = 89+ tid + 4;}

    printf("befor the barrier y: %d, tid:%d\n", y,tid);

    #pragma omp barrier
    printf("after the barrier y: %d, tid:%d\n", y,tid);

    if(tid==1)
    {
        x = x + y;
        printf("value %d\n", x);
    }
}
}

output :

befor the barrier y: 10, tid:0
befor the barrier y: 25, tid:1
after the barrier y: 25, tid:0
after the barrier y: 25, tid:1
value 25

In the above code and output, why the y value is didn't get updated from 25 to 10 in the thread id 0, after the barrier?. I am totally confused.. somebody please explain me that what's happening.

Thanks

Was it helpful?

Solution

The following sequence of events will produce the output you see.

  1. thread 0 executes y = 25;
  2. thread 0 executes y = 10;
  3. thread 0 executes printf("befor the barrier y: %d, tid:%d\n", y,tid);
  4. thread 1 executes y = 25;
  5. thread 1 executes printf("befor the barrier y: %d, tid:%d\n", y,tid);
  6. both threads exit barrier
  7. thread 0 executes printf("after the barrier y: %d, tid:%d\n", y,tid);
  8. thread 1 executes printf("after the barrier y: %d, tid:%d\n", y,tid);

This sequence of events is not at variance with the requirements of OpenMP.

The barrier ensures that all threads wait at the barrier until the last thread catches up at which point all threads may continue computing. The barrier does not affect the sequencing of events on different threads prior to their reaching it, nor indeed after they have left it. The barrier guarantees that all threads have executed all (their share of) the code prior to the barrier, but no more than that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top