How can I tell if a ref is being updated by a dosync in Clojure?

孤者浪人 提交于 2019-12-23 17:47:08

问题


I have some updates which need to be made to a ref, but I want to choose a time to perform the updates when the ref is not in heavy use. Is there a way I can programatically tell when the ref is in a transaction?


回答1:


you could add-watch that would update an access-time each time your ref is written (you mentions it was write mostly). This would give you a huristic for busy.

(def my-ref (ref {}))
(def my-ref-atime (atom 0))
(add-watch my-ref (fn [key ref old new] (swap! my-ref-atime current-time-fn)))) 

then only do low priority work when atime is more than 10ms in the past.




回答2:


You may be asking a single identity to do too much. Consider having two identities: one that has high write volume, and another (possibly derivative) identity that is updated occasionally.

Your approach already implies that the occasional updates aren't part of the ref's timeline, since you are willing to defer them.




回答3:


Are you sure you want to use a ref and not an agent?

It sounds to me like you want to perform updates, but you don't care about when the updates actually happen (just so long as they happen eventually). This is exactly what agents are used for: sharing state in an asynchronous and independent manner. Refs are for sharing state in a synchronous and coordinated manner.

Structuring application logic around whether or not a ref is in a transaction sounds like a bad idea to me. Maybe if you provide more details someone can come up with a better design.



来源:https://stackoverflow.com/questions/5583860/how-can-i-tell-if-a-ref-is-being-updated-by-a-dosync-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!