2013-03-16 1 views
1

은의 Clojure REPL비교 설정! 무조건 clojure에서 원자를 재설정하려면?

(def elems (atom {})) 
(swap! elems assoc 42 [:a 7]) 
elems 

예상 {42 [:a 7]} 생산 코드의 다음과 같은 순서를 고려하십시오. 이제

(compare-and-set! elems elems (atom {})) 

compare-and-set! 작업이 성공하지 못했습니다 의미 false 해보세요. 나는 elemscompare-and-set! 작업 내에서 elems과 동일하게 테스트 될 것으로 예상했기 때문에 놀랐습니다. 나는 무조건 원자를 리셋한다는 목표를 달성하기 위해 reset!을 사용할 수 있다는 것을 알고 있지만, 왜 compare-and-set!이 정확히 동일한 일을하지 않는지 알고 싶습니까?

답변

5

compare-and-set!은 원자가 아닌 원자가 참조하는 값에서 작동합니다.

clojure.core/compare-and-set! 
([atom oldval newval]) 
    Atomically sets the value of atom to newval if and only if the 
    current value of the atom is identical to oldval. Returns true if 
    set happened, else false 

아마 당신이 원하는 :

(compare-and-set! elems @elems {}) 
관련 문제