简体   繁体   English

Scala中Clojure的并发原语的真正替代品

[英]Real alternatives to Clojure's concurrency primitives in Scala

In Clojure I have four primitives to manage concurrency scenarios 在Clojure中,我有四个原语来管理并发场景

  1. Refs - manage coordinated, synchronous changes to shared state Refs - 管理对共享状态的协调,同步更改
  2. Atoms - manage uncoordinated, synchronous changes to shared state 原子 - 管理对共享状态的不协调的同步更改
  3. Agents - manage asynchronous changes to shared state 代理 - 管理对共享状态的异步更改
  4. Vars - manage thread-local state Vars - 管理线程本地状态

My questions is - is there a mature equivalent to each of these in Scala? 我的问题是 - Scala中是否有成熟的等价物?

Assumptions - I'm going to assume that: 假设 - 我将假设:

  • Actors are a different way to solve the problems that agents do - but they are no means a drop-in replacement 演员是解决代理人所遇问题的另一种方式 - 但他们并不意味着直接替代
  • I'm aware there are agent libraries in Scala - I'm curious to know if they're considered mature 我知道Scala中有代理库 - 我很想知道它们是否被认为是成熟的

Most of the concurrency constructs you listed for Clojure are based in software transactional memory. 您为Clojure列出的大多数并发结构都基于软件事务内存。 Because of that, I think you're basically just asking about STM support in Scala. 因此,我认为你基本上只是在询问Scala中的STM支持。 According to the Akka documentation , the best choice for STM in Scala is ScalaSTM , and they say it's actually going to be included in the Scala Standard Library sometime in the future. 根据Akka文档 ,Scala中STM的最佳选择是ScalaSTM ,他们说它实际上将在未来的某个时间包含在Scala标准库中。

ScalaSTM supports Agents and Refs (which I believe were actually based on the Clojure versions). ScalaSTM支持代理和引用(我认为它实际上基于Clojure版本)。 I think the corollary of an Atom would be the Ref.single type, which is just a ref that you can use outside of an atomic block. 我认为Atom的推论是Ref.single类型,它只是一个可以在atomic块之外使用的ref。

Depending on your use case, a good substitute for var would be Java's ThreadLocal or Scala's DynamicVariable . 根据您的使用情况, var一个很好的替代品是Java的ThreadLocal或Scala的DynamicVariable Use ThreadLocal if all you want is thread-local data, but if you actually need dynamic binding, then I think you need DynamicVariable . 如果您想要的只是线程本地数据,请使用ThreadLocal ,但如果您确实需要动态绑定,那么我认为您需要DynamicVariable

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

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