Create a gist now

Instantly share code, notes, and snippets.

swap vs. reset
; First with reset! (don't do this!)
user=> (defn id-generator []
(let [id (atom 0)]
(fn []
(reset! id (inc @id)))))
#'user/id-generator
user=> (def g (id-generator))
#'user/g
user=> (doseq [i (range 10)]
(future
(doseq [j (range 5000)] (g))
(println i " done")))
nil
0 done
5 done
8 done
2 done
1 done
7 done
4 done
9 done
6 done
3 done
user=> (g)
9095 <<<----- WTFBBQ?!?!?
;; Now with swap!
user=> (defn id-generator []
(let [id (atom 0)]
(fn []
(swap! id inc))))
#'user/id-generator
user=> (def g (id-generator))
#'user/g
user=> (doseq [i (range 10)]
(future
(doseq [j (range 5000)] (g))
(println i " done")))
0 done
2 done
1 done
3 done
7 done
5 done
4 done
nil
6 done
9 done
8 done
user=> (g)
50001 <<<--- That's better.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment