Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threadsafe pop in clojure?

I've found this code on http://www.learningclojure.com/2010/11/yet-another-way-to-write-factorial.html, but I don't understand if/how the pop-task is supposed to be threadsafe. Doesn't it allow to return twice the same head ?

(def to-do-list (atom '()))  
(defn add-task![t] (swap! to-do-list #(cons t %)))  
(defn pop-task![] (let [h (first @to-do-list)] (swap! to-do-list rest) h))

If so, is it possible to keep using atom and write the peek and swap! atomically, or is this a job for the ref mechanism ?

like image 844
Cédric Pineau Avatar asked Feb 25 '23 11:02

Cédric Pineau


1 Answers

Or you drop to a lower level.

(def to-do-list (atom nil))

(defn add-task!
   [t]
   (swap! to-do-list conj t))

(defn pop-task!
   []
   (let [[h & r :as l] @to-do-list]
     (if (compare-and-set! to-do-list l r)
       h
       (recur))))
like image 99
kotarak Avatar answered Mar 02 '23 14:03

kotarak