small medium large xlarge

29 Oct 2015, 20:55
Rafal Spacjer (1 post)


I’ve been reading your book and so far I enjoy it a lot. Good job :)

In the book, you have defined such function:

(defn assign-item-to-child [child]
  (let [item (first @shopping-list)]
    (alter assignments assoc child item)
    (alter shopping-list disj item))

I’m curios what will happen if many threads invoke it simultaneous. Could it happen that many threads will have the same value in the item symbol? If so, we would assign the same item to many kids. Shouldn’t we invoke (first @shopping-list) in the dosync block? Or maybe we should first (ensure shopping-list) and then take the first item from this list?

08 Nov 2015, 20:25
Dan js (1 post)

I was going to ask the sane

Current-profile (1)_pragsmall
07 Jan 2016, 18:27
Ben Vandgrift (3 posts)

Thanks! I’m glad you’re finding it useful.

With the let outside of the dosync block, it may execute prior to the start of the transaction, allowing other transactions to capture the same value. Moving the let within the dosync will ensure that the value of shopping-list set doesn’t change save via the alter shopping-list ,,,.

The alter shopping-list ,,, adds the list to the set of locked references within the transaction, so the ensure isn’t necessary.

I’ve put a gist demonstrating this out there for review.

Thanks for the question! And now we’ll need to update that section.

You must be logged in to comment