Reduction

Reduction operation is widely used to gather values of some variable stored on different threads.

import java.io.IOException;
import org.pcj.*;

@RegisterStorage(PcjReduction.Shared.class)
public class PcjReduction implements StartPoint {

@Storage(PcjExample.class)
enum Shared { a }
public long a;

public static void main(String[] args) throws IOException {
    String nodesFile  = "nodes.txt";
    PCJ.executionBuilder (PcjExample.class)
                .addNodes(new File("nodes.txt"))
                .start();
}

@Override
public void main() throws Throwable {
    a = PCJ.myId() + 10;    // set value of a
    long sum = 0;
    
    if (PCJ.myId() == 0) {
      sum = PCJ.reduce(Lomg::sum, Shared.a);
   }
   PCJ.barrier();
   System.out.println(PCJ.myId()+ " "+ sum);
}
}

In the presented example the values are communicated to the thread with the id 0. Than reduction operation such as summation is performed. Than value of the variable a (Shared variable) stored at the thread p is communicated to the thread 0 and added to the local variable sum.

The presented algorithm of the reduction is based on the synchronous communication PCJ.get(). The summation is performed at thread 0 as data is arrived.

The asynchronous version requires additional storage at the thread 0. The al[]variable stores values of a variable communicated in asynchronous way:

Last updated

Was this helpful?