Skip to content

Instantly share code, notes, and snippets.

@aphyr
Created April 15, 2016 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aphyr/8746181beeac6a728a3aa018804d56f6 to your computer and use it in GitHub Desktop.
Save aphyr/8746181beeac6a728a3aa018804d56f6 to your computer and use it in GitHub Desktop.
Clojure range (next) thread safety issue?
FAIL in (range-test) (range_test.clj:18)
expected: 1000
actual: 927
Ran 1 tests containing 1 assertions.
1 failures, 0 errors.
Reloading scratch.range-test ... done.
Testing scratch.range-test
FAIL in (range-test) (range_test.clj:18)
expected: 1000
actual: 351
Ran 1 tests containing 1 assertions.
1 failures, 0 errors.
Reloading scratch.range-test ... done.
Testing scratch.range-test
FAIL in (range-test) (range_test.clj:18)
expected: 1000
actual: 223
(ns scratch.range-test
(:require [clojure.test :refer :all]))
(deftest range-test
(let [threads 10
n 1000
r (atom (range (inc n)))
m (atom 0)]
; Iterate through the range concurrently,
; updating m to the highest seen value in the range
(->> (range threads)
(map (fn [id]
(future
(loop []
(when-let [r (swap! r next)]
(swap! m max (first r))
(recur))))))
(map deref)
dorun)
(is (= n @m))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment