Channel Synchronization in Chapel

Channel synchronization in Chapel can be achieved using synchronization variables. Here’s an example of using a synchronization variable to wait for a task to finish. When waiting for multiple tasks to finish, you may prefer to use a sync block.

use Time;

// This is the procedure we'll run in a task. The
// 'done' sync variable will be used to notify another
// task that this procedure's work is done.
proc worker(ref done: sync bool) {
  write("working...");
  sleep(1);
  writeln("done");

  // Set the sync variable to true to notify that we're done.
  done = true;
}

proc main() {
  // Create a sync variable
  var done: sync bool;

  // Start a worker task, giving it the sync variable to
  // notify on.
  begin worker(done);

  // Block until we receive a notification from the
  // worker through the sync variable.
  done;
}

To run the program:

$ chpl channel-synchronization.chpl
$ ./channel-synchronization
working...done

If you removed the done; line from this program, the program would exit before the worker even started.

In this Chapel version:

  1. We use a sync bool variable instead of a channel for synchronization.
  2. The worker procedure takes a reference to the sync variable.
  3. We use begin to start an asynchronous task instead of a goroutine.
  4. The main task waits for the worker by reading from the sync variable.

This example demonstrates how Chapel’s synchronization variables can be used to coordinate between tasks, similar to channel synchronization in other languages.