📅  最后修改于: 2023-12-03 14:59:56.724000             🧑  作者: Mango
Atoms are essential for concurrent programming in Clojure as they provide a way to update values in a thread-safe manner without locking. They are a form of reference type along with refs, vars, and agents. Atoms are designed to hold a single value and provide two main functions: swap!
and reset!
.
An atom can be created using the atom
function. Let's create an atom holding the value of 0:
(def my-atom (atom 0))
swap!
The swap!
function is used to modify the value of an atom. It takes two arguments: the atom and a function which takes the current value of the atom and returns the updated value.
(swap! my-atom inc)
;; the value of my-atom is now 1
Here, the inc
function is used to increment the current value of the atom by 1.
reset!
The reset!
function is used to set the value of an atom to a new value.
(reset! my-atom 10)
;; the value of my-atom is now 10
Let's look at an example where we use an atom to keep track of a counter that is incremented every time a button is pressed.
(def counter (atom 0))
(defn handle-button-click []
(swap! counter inc))
;; every time the button is clicked, handle-button-click is called
(handle-button-click) ;; the value of counter is now 1
(handle-button-click) ;; the value of counter is now 2
The current value of an atom can be obtained using the deref
function or the @
reader macro.
(deref my-atom) ;; returns the current value of my-atom
@my-atom ;; equivalent to (deref my-atom)
Atoms are a powerful tool for concurrent programming in Clojure. They provide a way to update values in a thread-safe manner without locking. Atoms are easy to create and use, and they have two main functions: swap!
and reset!
. When used correctly, atoms can make writing concurrent programs simpler and less error-prone.