multithreading - Best way to remove item in a list for an atom in Clojure -


i'm using server.socket stream data multiple clients, server.socket uses threads each client connection. have this:

(def clients (atom ())) ; connected clients defined globally namespace  (swap! clients conj a)  ; adds client (which atom well), in function run on client's thread  ;i want better process of removing client! (dosync (reset! clients (remove #{a} @clients))) ; removes client list, run in function on client's thread 

i run function runs through each client , grabs content, in infinite loop on each of multiple client threads, it's run simultaneously:

(doseq [c @clients]   (print ((deref c) :content))   (flush)) 

i sort of came conclusion using atoms in threads makes program work smoothly , allows non-blocking reads, i'm happy except feel resetting global client's atom can remove single client list bad move. there more appropriate way accomplish using swap! ? chose list clients atom i'm running doseq on each connected client grab content , flush output stream socket.

avoid deref-ing atom within swap! or reset!.

here swap! going give need. takes function receives current value, can use update:

(def clients (atom '(:a :b :c :d))) (swap! clients (fn [s] (remove #{:a} s))) 

you may used not seeing function argument of swap! explicitly above because swap! apply function additional args provided, if in correct order, e.g. if used set clients, can

(def clients (atom #{:a :b :c :d})) (swap! clients disj :a) 

Comments