在Scala循环中为多线程创建ForkJoinTask时的奇怪行为

时间:2016-09-21 05:04:27

标签: multithreading scala scala-collections fork-join

工作是转换src数组中的值并将新值写入dst数组。

当我在while循环中创建ForkJoinTasks时

val height: Int = 4;
val numTasks: Int = 2;

var tasks = scala.collection.mutable.ListBuffer.empty[ForkJoinTask[Unit]]

val jump: Int = src.height / numTasks
var from: Int = 0;

while (from < height) {
  val end: Int = height.min(from + jump);
  val t: ForkJoinTask[Unit] = task {
    run(src, dst, from, end) // (2,2), (2,1), what is happening?
  }
  from = end
}

for (t <- tasks.toList) {
  t.join()
}

然后奇怪的是,run函数将(from,end)参数值取为(2,2)。但如果我将它手动分成两个任务,那么它正常工作,如(0,1)和(1,2)。

val t1 = task {
  run(src, dst, 0, height / 2); // (0, 1)
}
val t2 = task {
  run(src, dst, height / 2, height); // (1, 2)
}

t1.join()
t2.join()

我很难弄清楚发生了什么。这是我的第一个Scala程序,所以我可能会遗漏一些非常微不足道的东西。任何评论都将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:0)

删除对src或dst的引用似乎没问题,因为返回范围

0 2
2 4

import shapeless.PolyDefns.~>
import shapeless.{ HList, HNil }
import io.netty.util.internal.chmv8.ForkJoinTask

object main extends App {

  val height: Int = 4;
  val numTasks: Int = 2;

  var tasks = scala.collection.mutable.ListBuffer.empty[ForkJoinTask[Unit]]

  val jump: Int = height / numTasks
  var from: Int = 0;

  while (from < height) {
    val end: Int = height.min(from + jump);
    val t: ForkJoinTask[Unit] =  {
      run( from, end) // (2,2), (2,1), what is happening?
    }
    from = end
  }

  for (t <- tasks.toList) {
    t.join()
  }


  def run (from: Int, end:Int) ={
    println(s"$from $end")
    null
  }

}