简体   繁体   English

Scala期货和多线程

[英]Scala Futures and Multithreading

I am new to Scala and I'm trying to get an handle on futures and multithreading 我是Scala的新手,我正在尝试了解期货和多线程

I have a SingleThreaded version of a program that makes some calculations on a matrix 我有一个单线程版本的程序,可以在矩阵上进行一些计算

SingleThreadCalc {
  def run(matrix : Seq[Seq[Double]]) : Future[Seq[Seq[Double]] = Future{doMath(matrix)}
}

What i want now is to make a multithreaded version of it. 我现在想要的是制作一个多线程版本。 is it enought to just pass an ExecutionContext with a number of threads? 仅通过带有多个线程的ExecutionContext就足够了吗?

MultiThreadCalc {
  def run(matrix : Seq[Seq[Double]]) : Future[Seq[Seq[Double]] = 
Future{doMath(matrix)} (ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)))

Will this share the computation load between all the threads or is it not happening at all? 这会在所有线程之间分担计算负担吗?还是根本不会发生?

Short answer: No. 简短答案:不可以。

Long answer: 长答案:

object MultiThreadCalc {
 def run(matrix : Seq[Seq[Double]]) : Future[Seq[Seq[Double]] = 
    Future{doMath(matrix)}(ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)))
}

The code above will, for every invocation of run , will allocate a new thread pool which will never be shut down, and it will be used to execute a single method doMath (so only 1 thread in that pool will be used). 上面的代码将为run每次调用分配一个永远不会关闭的新线程池,它将用于执行单个方法doMath (因此该池中仅使用1个线程)。

Now, if you want to parallelize execution of doMath itself, then you'll need to modify ts definition to be parallelizable, possibly by making it take an implicit ec: ExecutionContext parameter and using that within its definition. 现在,如果要并行化doMath本身的执行,则需要将ts定义修改为可并行化,可能是使其采用implicit ec: ExecutionContext参数并在其定义中使用该参数。

But if you instead want to be able to run many invocations of doMath in parallel then you can do the following: 但是,如果您希望能够并行运行许多doMath调用,则可以执行以下操作:

object MultiThreadCalc {
  def run(matrix : Seq[Seq[Double]])(implicit ec: ExecutionContext) : Future[Seq[Seq[Double]] = Future{doMath(matrix)}
}

And then create an ExecutionContext possibly ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)) on the "outside" and use it whenever you want to execute logic on it. 然后在“外部”上创建一个ExecutionContext(可能是ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)) ,并在您要对其执行逻辑时使用它。

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

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