如何设置并行集合的线程号? [英] How to set thread number for the parallel collections?

查看:70
本文介绍了如何设置并行集合的线程号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以像这样并行运行scala的foreach:

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 number? I want something like that:

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

推荐答案

每个并行集合都保留一个tasksupport对象,该对象保留对线程池实现的引用.

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

因此,您可以根据需要通过将tasksupport对象的引用更改为新的线程池来设置该对象的并行度.例如:

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)

有关配置并行集合的更多信息,您可以参考 http://docs.scala-lang.org/overviews/parallel-collections/configuration.html

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

这篇关于如何设置并行集合的线程号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆