Should multiple Clojure refs be read in a transact

2019-06-22 15:59发布

问题:

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.