How to set thread number for the parallel collections?

前端 未结 2 1983
粉色の甜心
粉色の甜心 2021-02-19 23:35

I can run scala\'s foreach in parallel like that:

val N = 100
(0 until N).par.foreach(i => {
   // do something
})

But how can I set thread

2条回答
  •  你的背包
    2021-02-19 23:38

    Every parallel collection keeps a tasksupport object which keeps a reference to thread pool implementation.

    So, you can set the parallelism level through that object by changing the reference of tasksupport object to a new thread pool according to your need. eg:

    def f(numOfThread: Int, n: Int) = {
     import scala.collection.parallel._
     val coll = (0 to n).par
     coll.tasksupport = new ForkJoinTaskSupport(new scala.concurrent.forkjoin.ForkJoinPool(numOfThreads))
      coll.foreach(i => {
       // do something
      })
    }
    
    f(2, 100)
    

    For more info on configuring parallel collections you can refer http://docs.scala-lang.org/overviews/parallel-collections/configuration.html

提交回复
热议问题