Skip to content

Instantly share code, notes, and snippets.

@ymurase
Last active August 29, 2015 14:11
Show Gist options
  • Save ymurase/a830fac303e611f500f1 to your computer and use it in GitHub Desktop.
Save ymurase/a830fac303e611f500f1 to your computer and use it in GitHub Desktop.
x10 fibonacci calculation using GLB
import x10.glb.ArrayListTaskBag;
import x10.glb.TaskQueue;
import x10.glb.TaskBag;
import x10.glb.GLBParameters;
import x10.glb.GLB;
import x10.util.Team;
import x10.glb.Context;
import x10.glb.ContextI; // ContextI : Interface for Context
import x10.glb.GLBResult;
public class FibG {
class FibTQ implements TaskQueue[FibTQ, Long] {
val bag = new ArrayListTaskBag[Long](); // TaskBagをArrayListで実装したクラス。型パラメータはtaskに与えるパラメータ
var result:Long = 0;
public def init(n: Long) {
bag.bag().add(n); // ArrayListに追加
}
public def process(var n:Long, context: Context[FibTQ,Long]):Boolean {
val b = bag.bag(); // ArrayListのreference
for( var i:Long = 0; bag.size() > 0 && i < n; i++) {
val x = b.removeLast();
if( x < 2 ) result += x;
else {
b.add(x-1);
b.add(x-2);
}
context.yield(); // context switchingが可能なpoint。これが無いとtaskがstealされず1プロセスしか使えない。
}
return b.size() > 0;
}
// return the number of task items that have been processed.
public def count() {
return 0;
}
// Merge TaskBag into the current task bag , thus changing the state of current taskbag.
// ArrayListTaskBag を使っている場合は丸ごとコピーでOKなはず。
public def merge( var _tb: TaskBag): void {
this.bag.merge( _tb as ArrayListTaskBag[Long]);
}
// Split local bag into two and return half of it
// ArrayListTaskBag を使っている場合は丸ごとコピーでOK。
public def split(): TaskBag {
return this.bag.split();
}
// 実装してもしなくてもよい。
public def printLog(): void {
}
var fr:FibResult = null;
public def getResult(): FibResult {
if( fr == null ) {
fr = new FibResult();
}
return fr;
}
class FibResult extends GLBResult[Long] {
var r:Rail[Long] = null;
public def getResult():x10.lang.Rail[Long] {
r = new Rail[Long](1);
r(0) = result;
Console.OUT.println("local result: " + r(0) );
return r;
}
public def getReduceOperator():Int {
return Team.ADD;
}
public def display(r:Rail[Long]):void {
Console.OUT.println("Inside display: " + r(0));
}
}
}
public def run(n:Long):Rail[Long] {
val init = () => { return new FibTQ(); }; // initは各Placeで実行されるのでclosureを渡す?
val glb = new GLB[FibTQ, Long](init, GLBParameters.Default, true);
Console.OUT.println("Starting...");
var time:Long = System.nanoTime();
val start = () => { (glb.taskQueue()).init(n); };
return glb.run(start);
}
public static def main(args:Rail[String]) {
val N = args.size < 1 ? 10 : Long.parseLong(args(0));
val result = new FibG().run(N);
Console.OUT.println("fib-glb(" + N + ")" + result(0) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment