Scala 中的并发会自动发生吗? [英] Does concurrency in Scala happen automatically?

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

问题描述

在 Scala 中,当您编写一个没有副作用且引用透明的函数时,是否意味着运行时环境会自动将其处理分配给多个线程?

In Scala, when you write a function that has no side effect and is referentially transparent, does that mean, that the runtime environment automatically distributes it's processing to multiple threads?

推荐答案

不,通常不是这样,除非您以某种方式明确指定要并行处理(例如 ScalaCL,并行集合).它很难甚至不可能自动执行,例如:

No, usually it does not mean so, unless you explicitly specify somehow that you want parallel processing (e.g. ScalaCL, parallel collections). It will be hard to impossible to it do automatically, for example:

def foo() = {
  val x = 1 + 2
  val y = 2 + 3
  x + y
}

尽管 x 和 y 的计算可以并行化,但实际上它比串行代码更慢(由于并行化产生的惩罚).因此,通过自动并行化所有内容,您最终会得到基本单元的非常低效的代码.

Although, calculation of x and y can be parallelized, in practice it will be even slower (due to penalty incurred in parallelization) than serial code. So with automatic parallelization of everything you will end up with highly ineffective code for basic units.

您可以说:为什么不自动选择性地并行化代码(例如,不值得时不并行化),但是这样的系统必须依赖数十亿个因素,最重要的是将是特定的架构、当前的操作系统负载、运行配置文件等等(我想最终,我们将不得不解决 暂停问题).而这个神奇的追踪系统会涉及到它自己的惩罚.

You can say: why don't you parallelize code automatically and selectively (e.g. do not parallelize when it is not worth it), but such system have to rely on billions of factors, most important will be a specific architecture, current OS load, running profile, and many more (I guess in the end, we will have to solve halting problem). And this magic tracking system will involve it's own penalty.

最后,虽然有效果分型研究,但 Stock scala 没有任何办法区分副作用函数和非副作用函数.

Finally, although there is effect typing research, stock scala do not have any ways to make a distinction between side-effecting and non-side effecting functions.

毕竟,正如@fracca 所展示的那样,手动并行化 Scala 代码并不难.

After all, it is not that hard to parallelize scala code manually, as @fracca demonstrated.

这篇关于Scala 中的并发会自动发生吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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