Shared variables

The general rule is that variables are local to the tasks and cannot be accessed from another task. PCJ offers possibility to mark some variables Sharedusing Java annotation mechanism. The Shared variables are accessible across tasks, eg. one task can get access to the shared variable instance stored in another task. Shared variables have to be defined as part of enum variable and have to be registered using @RegisterStorage annotation.

@RegisterStorage(ExampleGetPut.Shared.class)    // Register storage 
public class ExampleGetPut implements StartPoint {

    @Storage(ExampleGetPut.class)               // Define storage
    enum Shared {
        a, array

    public double a = PCJ.threadCount();
    public double array[] = new double[10];

The elements of Shared variable can be single variables, arrays as well as more complicated objects.

Access to a shared variables

The PCJ librrary provides methods to access shared variables, eg. to get value stored in the memory of another task (get()) or to modify variable located in the memory of another task (put()).

Both methods: get(} and put() perform one-sided communication. This means, that access to the memory of another task is performed only by task which executes get or put methods. The task which memory is contacted do not need to execute these methods.

The example code presents how to assign value of the variable a at task 3 to the variable c at task 0.

if (PCJ.myId()==0) c = (double) PCJ.get(3, Shared.a);

The same for assigning value of the variable array[2]at task 3 to the variable c at task 0.

if (PCJ.myId()==0) c = (double) PCJ.get(3, Shared.array, 3);

Next example presents how to assign value 3.0 to the variable a available at the task 5. This operation is performed by the task 0.

if (PCJ.myId()==0) PCJ.put(3.0, 5, Shared.a);

Simmilar, we send value of 4.0 to the array[] stored at the thask 2. The array[1] element is updated.

if (PCJ.myId()==0)PCJ.put(4.0, 2, Shared.array, 1);

The communication is performed in synchronous way. The asyncPut() and asyncGet() can be used for asynchronous communication which means that user has no guarantee that value has been changed or transferred from remote task. The use of asynchronous communication may cause some problems, especially for non experienced users. PCJ provides additional methods to solve this problem.

Last updated