Should multiple Clojure refs be read in a transact

2019-06-22 16:00发布

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条回答
对你真心纯属浪费
2楼-- · 2019-06-22 16:15

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.

查看更多
登录 后发表回答