简体   繁体   English

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

[英]Strange behavior when creating ForkJoinTask for multithreading in Scala loop

The job is to convert the values from the src array and write the new values to the dst array. 工作是转换src数组中的值并将新值写入dst数组。

When I create ForkJoinTasks in a while loop 当我在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()
}

Then strangely, the run function takes the (from, end) arguments value as (2, 2). 然后奇怪的是,运行函数将(从(起始),结束)参数值取为(2,2)。 But If I split it manually into two tasks, then it works normally, as (0,1) and (1,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()

I am having hard time to figure out what is going on. 我很难弄清楚发生了什么。 This is my very first Scala program, so I might be missing something very trivial. 这是我的第一个Scala程序,所以我可能缺少一些琐碎的东西。 Any comment would be appreciated. 任何意见,将不胜感激。

Thank you. 谢谢。

Removing references to src or dst your code seems ok as returns ranges 删除对src或dst代码的引用似乎不错,因为返回范围

0 2 0 2
2 4 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
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM