upc_barrier

Phil Merkey

Introduction

This page shows the use of upc_barrier. The typical use of a barrier is at the bottom of a parallel loop.

This page shows a bad use of barriers. It serializes the helloworld program. We have used this example to show syntax of a upc_barrier and point out that this is a good debugging trick.

A use of a barrier marks a synchronization phase. All threads have to reach the barrier before any thread leaves. Barriers in UPC take an argument which can give useful debugging information. In the following code, all threads hit upc_barrier(1) THREADS number of times before moving on the second loop. If one were to uncomment the single call to upc_barrier(3) there would be a detectable runtime error in the second loop.

<upc-barriers.c>=
#include <stdio.h>
#include <upc.h>

main ()
{
  int t;
  for( t=0; t<THREADS; t++ ) {
    upc_barrier(1);
    if( t == MYTHREAD )
      printf ("Hello: Process %d of %d\n", MYTHREAD, THREADS);
  }
 // uncomment this a see what happens
 //if(MYTHREAD==0){upc_barrier(3);} 

  for( t=THREADS-1; t>=0; t-- ) {
    upc_barrier(2);
    if( t == MYTHREAD )
      printf ("Goodbye: Process %d of %d\n", MYTHREAD, THREADS);
  }
}

This serialization trick is a good thing to keep in mind when debugging a complicated block that might contain a race condition. That is, suppose that the print statement was instead a complicated block of code that you thought was race free, but was misbehaving. You could wrap the the block with this for; upc_barrier; if(t==MYTHREAD) { construct to get serial execution without changing the block of code. Running the code in a serial fashion should give some debugging information.