Scala 中的并发映射/foreach [英] Concurrent map/foreach in scala

查看:22
本文介绍了Scala 中的并发映射/foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个迭代 vals: Iterable[T] 和一个没有任何相关副作用的长时间运行的函数:f: (T => Unit).现在这以明显的方式应用于 vals :

I have an iteration vals: Iterable[T] and a long-running function without any relevant side effects: f: (T => Unit). Right now this is applied to vals in the obvious way:

vals.foreach(f)

我希望对 f 的调用同时进行(在合理范围内).Scala 基础库中某处是否有明显的函数?类似的东西:

I would like the calls to f to be done concurrently (within reasonable limits). Is there an obvious function somewhere in the Scala base library? Something like:

Concurrent.foreach(8 /* Number of threads. */)(vals, f)

虽然 f 运行时间相当长,但它足够短,我不希望为每次调用调用一个线程的开销,所以我正在寻找基于线程池的东西.

While f is reasonably long running, it is short enough that I don't want the overhead of invoking a thread for each call, so I am looking for something based on a thread pool.

推荐答案

我喜欢 Futures 的答案.但是,虽然它会并发执行,但也会异步返回,这可能不是您想要的.正确的方法如下:

I like the Futures answer. However, while it will execute concurrently, it will also return asynchronously, which is probably not what you want. The correct approach would be as follows:

import scala.actors.Futures._

vals map { x => future { f(x) } } foreach { _() }

这篇关于Scala 中的并发映射/foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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