HC keywords in a nutshell:

A simple HelloWorld example


In this simple example, we create an asynchronous task using an async block, which contains the code to display "HelloWorld". A finish block wraps the async which allows to wait for its complete execution before proceeding to the return statement.

#include <stdio.h>
int main (int argc, char ** argv) {
  finish {
    async {
      printf("Hello World !\n");
    }
  }
  return 0;
}

Passing arguments to Asyncs

An async only knows about global variables and variables passed as a parameter to it (similarly to function calls). We use a set of three clauses: IN, OUT and INOUT to specify how the code within asyncs interacts with variables declared in their enclosing lexical scope.

The variable copy in IN, OUT and INOUT clauses is shallow: pointers are only copied by value.

Passing async's arguments by value

Next example shows how to write a simple parallel for loop. The loop's body contains an async to be spawned at each iteration. One can picture the execution of this code as if each iteration copies the current value of IN arguments, creates the async and then schedule it for execution. Note that since 'i' is passed by value, the variable can be freely modified inside and outside the async body. However 'j' is not declared as an IN argument, hence it is not visible in the async's body.

#include <stdio.h>
int main (int argc, char ** argv) {
  int i = 0, j = 0;
  finish {
    for(i=0; i < LG; ) {
      async IN(i) { // 'i' passed by value
        printf("Hello %d times !\n", i);
      }
      i++; // incr loop's 'i'
    }
  }
  return 0;
}

Interactions with the spawning environment

An async can interact with its spawning environment in various ways. Similarly to the C language, a pointer can be passed as an IN argument. Since variables are passed by shallow copy, several asyncs can share a pointer and access the same underlying memory. Note that the programmer is then responsible for avoiding race-condition on the accessed memory (See the "finish" and "phaser" construct to coordinate asyncs execution).

The OUT clause provides another way to interact with the spawning environment. It allows an async to write a value back to a variable listed in the clause. When a variable is listed in an OUT clause, its address is saved and a temporary, uninitialized variable of the same type is allocated in the async's body. The local variable can only be accessed in the async's body. Its value is written back to the saved address when the async has finished its execution.

int main (int argc, char ** argv) {
  int i = 0;
  finish {
    async OUT(i) {
      // local, uninitialized version of 'i'
      i = some_computation();
    }
    // 'i' value is undetermined as the async is executed concurrently
  }
  // 'finish' ensures the async is done.
  // 'i' value is guaranteed to have been written-back
  return 0;
}