Should multiple Clojure refs be read in a transaction for consistency?

感情迁移 提交于 2019-12-10 14:12:10

问题


This is a theoretical question motivated by my desire to understand Clojure's concurrency better.

Let's say I'm writing boids. Assume each boid is a separate green thread mutating positions in a vector or refs representing a world grid. Think Hickey's ants colony.

Now, documentation at Clojure.org states "All reads of Refs will see a consistent snapshot of the ‘Ref world’ as of the starting point of the transaction (its ‘read point’)."

Does this mean I can only get a consistent snapshot of my simulation, for example to draw it, by reading my vector of refs within a transaction (i.e. within a dosync context?)

Thanks!


回答1:


You need a transaction if you want a consistent snapshot.

If you read the refs outside a transaction, then you will just get an instantaneous value at the moment that you read each one. You have no guarantee that another transaction will not change one or more of the refs in between your reads, so you could end up with an inconsistent view.



来源:https://stackoverflow.com/questions/11985534/should-multiple-clojure-refs-be-read-in-a-transaction-for-consistency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!