sca*_*ape 4 multithreading atomic clojure
我正在使用server.socket将数据流式传输到多个客户端,server.socket为每个客户端连接使用Threads.我目前有这样的事情:
(def clients (atom ())) ; connected clients defined globally for that namespace
(swap! clients conj a)  ; adds a client (which is an atom itself as well), this is in a function that is run on the client's thread
;I want to better the process of removing a client!
(dosync (reset! clients (remove #{a} @clients))) ; removes client from list, run in a function on the client's thread
我运行一个遍历每个客户端并抓取内容的函数,它在每个多个客户端线程上处于无限循环中,因此它同时运行:
(doseq [c @clients]
  (print ((deref c) :content))
  (flush))
我在线程中使用Atoms的结论确实让程序顺利运行并允许非阻塞读取,所以我对此感到满意,除非我觉得重置全局客户端的Atom只是为了让我可以从中删除单个客户端这个名单是一个糟糕的举动.有没有更合适的方法来实现这一点使用交换!?我为clients atom选择了list,因为我在每个连接的客户端上运行doseq来获取内容并将其刷新到输出流套接字.
避免在一个swap!或多个内部使原子脱离reset!.
这swap!将给你你需要的东西.它需要一个接收当前值的函数,您可以将其用于更新:
(def clients (atom '(:a :b :c :d)))
(swap! clients (fn [s] (remove #{:a} s)))
您可能习惯于swap!不像上面那样明确地看到函数参数,因为swap!将函数应用于所提供的任何其他参数,因此如果它们的顺序正确,例如,如果我们使用set for clients,我们可以
(def clients (atom #{:a :b :c :d}))
(swap! clients disj :a)
| 归档时间: | 
 | 
| 查看次数: | 1218 次 | 
| 最近记录: |