如果我的问题不专业,请见谅。我正在阅读 IBM x10 的教程。这是计算 PI 但让我感到困惑的代码:
public static def countPoints(n: Int, rand: ()=>Double) {
var inCircle: Double = 0.0;
for (var j:Long = 1; j<=n; j++) {
val x = rand();
val y = rand();
if (x*x +y*y <= 1.0) inCircle++;
}
return inCircle;
}
val N = args.size() > 0 ? Long.parse(args(0)) : 100000;
val THREADS = args.size() > 1 ? Int.parse(args(1)) : 4;
val nPerThread = N/THREADS;
val inCircle = new Array[Long](1..THREADS);
finish for(var k: Int =1; k<=THREADS; k++) {
val r = new Random(k*k + k + 1);
val rand = () => r.nextDouble();
val kk = k;
async inCircle(kk) = countPoints(nPerThread,rand);
}
var totalInCircle: Long = 0;
for(var k: Int =1; k<=THREADS; k++) {
totalInCircle += inCircle(k);
}
val pi = (4.0*totalInCircle)/N;
程序本身并不难,我的问题是,由于在每个 countPoints() 调用它重复调用参数 rand,并且在产生多线程之前,只创建一个 rand,不同的线程会共享相同的 rand 并产生竞争条件吗?如果不是,为什么?