Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 863
Thomas Heywood Avatar asked Aug 16 '12 10:08

Thomas Heywood


1 Answers

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.

like image 176
mikera Avatar answered Oct 10 '22 02:10

mikera