Hello World for UPC

Phil Merkey

Introduction

Since UPC is an extension of C, every tutorial must start with Hello World. In C, the world most famous program looks like

<hello.c>=
#include <stdio.h>

main()
{
   printf("Hello World\n");
}

One usually compiles and runs the program with the commands:

% gcc hello.c
% ./a.out
Hello World

Hello World in UPC

In UPC, exactly the same code is a parallel program. We will use the command line syntax used by MuPC. Unfortunately, there is usual inconsistencies with the the command line syntax for various compilers.

% mupcc hello.c
% mupcrun -n 4 ./a.out
Hello World
Hello World
Hello World
Hello World

UPC is an SPMD programming language. The serial C version of hello world becomes a ``parallel program'' when the command mupcrun starts four copies of it. Using UPC terminology, each of these instantiations of the program is a called a thread. The next version of the ``Hello World'' uses the keywords THREADS and MYTHREAD to demonstrate this idea. Notice that we included the header file upc.h instead of stdio.h. This is required for all UPC programs that use upc keywords. The keyword THREADS can used as integer. It is set to the number of threads in the parallel execution. The keyword MYTHREAD is the thread id number so it has a value in the range 0 to THREADS-1.

<upc-hello.c>=
// Hello World that uses THREADS and MYTHREADS
#include <upc.h>

main()
{
  // one can use THREADS and MYTHREAD like ints

  if( MYTHREAD % 2 )
     printf("Hello world: I am thread %d and I am even.\n", MYTHREAD);
  else
     printf("Hello world: I am thread %d and I am odd.\n", MYTHREAD);
}

A typically execution of the code would look like:

% mupcc -f 4 upc_hello.c
% mupcrun -n 4 ./a.out
Hello world: I am thread 3 and I am odd.
Hello world: I am thread 0 and I am even.
Hello world: I am thread 2 and I am even.
Hello world: I am thread 1 and I am odd.

The order in which the threads print the message is completely arbitrary and non-deterministic.