在scala中并发地图/ foreach [英] Concurrent map/foreach in scala

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

问题描述

我有一个迭代 vals:Iterable [T] 和没有任何相关副作用的长时间运行函数: f:(T =单位)。现在,这以明显的方式应用于 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天全站免登陆