aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/concurrency/atom.lux
blob: 27bbe25fd3dd8733926835988840a00029d65bd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
(;module:
  lux
  (lux [io #- run]))

(type: #export (Atom a)
  {#;doc "Atomic references that are safe to mutate concurrently."}
  (#;Host "#Atom" (#;Cons a #;Nil)))

(def: #export (atom value)
  (All [a] (-> a (Atom a)))
  (_lux_proc ["atom" "new"] [value]))

(def: #export (get atom)
  (All [a] (-> (Atom a) (IO a)))
  (io (_lux_proc ["atom" "get"] [atom])))

(def: #export (compare-and-swap current new atom)
  {#;doc "Only mutates an atom if you can present it's current value.

          That guarantees that atom was not updated since you last read from it."}
  (All [a] (-> a a (Atom a) (IO Bool)))
  (io (_lux_proc ["atom" "compare-and-swap"] [atom current new])))

(def: #export (update f atom)
  {#;doc "Updates an atom by applying a function to its current value.

          If it fails to update it (because some other process wrote to it first), it will retry until it succeeds.

          The retries will be done with the new values of the atom, as they show up."}
  (All [a] (-> (-> a a) (Atom a) (IO Unit)))
  (io (let [old (_lux_proc ["atom" "get"] [atom])]
        (if (_lux_proc ["atom" "compare-and-swap"] [atom old (f old)])
          []
          (io;run (update f atom))))))

(def: #export (set value atom)
  (All [a] (-> a (Atom a) (IO Unit)))
  (update (function [_] value) atom))