aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/semaphore.lux
blob: fc6f939c872507775aa178e412e9d7fdac7ac75f (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
(.module:
  [library
   [lux #*
    [abstract
     [monad (#+ do)]]
    [control
     [pipe (#+ if>)]
     ["." io (#+ IO)]
     ["." try (#+ Try)]
     ["." exception (#+ exception:)]]
    [data
     [text
      ["%" format (#+ format)]]
     [collection
      ["." queue (#+ Queue)]]]
    [math
     [number
      ["n" nat]
      ["i" int]]]
    [type
     abstract
     ["." refinement]]]]
  [//
   ["." atom (#+ Atom)]
   ["." async (#+ Async Resolver)]])

(type: State
  {#max_positions Nat
   #open_positions Int
   #waiting_list (Queue (Resolver Any))})

(abstract: #export Semaphore
  (Atom State)

  {#.doc "A tool for controlling access to resources by multiple concurrent processes."}

  (def: most_positions_possible
    (.nat (\ i.interval top)))

  (def: #export (semaphore initial_open_positions)
    (-> Nat Semaphore)
    (let [max_positions (n.min initial_open_positions
                               ..most_positions_possible)]
      (:abstraction (atom.atom {#max_positions max_positions
                                #open_positions (.int max_positions)
                                #waiting_list queue.empty}))))

  (def: #export (wait semaphore)
    {#.doc (doc "Wait on a semaphore until there are open positions."
                "After finishing your work, you must 'signal' to the semaphore that you're done.")}
    (Ex [k] (-> Semaphore (Async Any)))
    (let [semaphore (:representation semaphore)
          [signal sink] (: [(Async Any) (Resolver Any)]
                           (async.async []))]
      (exec (io.run
             (with_expansions [<had_open_position?> (as_is (get@ #open_positions) (i.> -1))]
               (do io.monad
                 [[_ state'] (atom.update (|>> (update@ #open_positions dec)
                                               (if> [<had_open_position?>]
                                                    []
                                                    [(update@ #waiting_list (queue.push sink))]))
                                          semaphore)]
                 (with_expansions [<go_ahead> (sink [])
                                   <get_in_line> (in false)]
                   (if (|> state' <had_open_position?>)
                     <go_ahead>
                     <get_in_line>)))))
        signal)))

  (exception: #export (semaphore_is_maxed_out {max_positions Nat})
    (exception.report
     ["Max Positions" (%.nat max_positions)]))

  (def: #export (signal semaphore)
    {#.doc (doc "Signal to a semaphore that you're done with your work, and that there is a new open position.")}
    (Ex [k] (-> Semaphore (Async (Try Int))))
    (let [semaphore (:representation semaphore)]
      (async.future
       (do {! io.monad}
         [[pre post] (atom.update (function (_ state)
                                    (if (i.= (.int (get@ #max_positions state))
                                             (get@ #open_positions state))
                                      state
                                      (|> state
                                          (update@ #open_positions inc)
                                          (update@ #waiting_list queue.pop))))
                                  semaphore)]
         (if (is? pre post)
           (in (exception.except ..semaphore_is_maxed_out [(get@ #max_positions pre)]))
           (do !
             [_ (case (queue.peek (get@ #waiting_list pre))
                  #.None
                  (in true)

                  (#.Some sink)
                  (sink []))]
             (in (#try.Success (get@ #open_positions post)))))))))
  )

(abstract: #export Mutex
  Semaphore

  {#.doc "A mutual-exclusion lock that can only be acquired by one process at a time."}

  (def: #export (mutex _)
    {#.doc (doc "Creates a brand-new mutex.")}
    (-> Any Mutex)
    (:abstraction (semaphore 1)))

  (def: acquire
    (-> Mutex (Async Any))
    (|>> :representation ..wait))

  (def: release
    (-> Mutex (Async Any))
    (|>> :representation ..signal))

  (def: #export (synchronize mutex procedure)
    {#.doc (doc "Runs the procedure with exclusive control of the mutex.")}
    (All [a] (-> Mutex (IO (Async a)) (Async a)))
    (do async.monad
      [_ (..acquire mutex)
       output (io.run procedure)
       _ (..release mutex)]
      (in output)))
  )

(def: #export limit
  {#.doc (doc "Produce a limit for a barrier.")}
  (refinement.refinement (n.> 0)))

(type: #export Limit
  {#.doc (doc "A limit for barriers.")}
  (:~ (refinement.type limit)))

(abstract: #export Barrier
  {#limit Limit
   #count (Atom Nat)
   #start_turnstile Semaphore
   #end_turnstile Semaphore}

  {#.doc "A barrier that blocks all processes from proceeding until a given number of processes are parked at the barrier."}

  (def: #export (barrier limit)
    (-> Limit Barrier)
    (:abstraction {#limit limit
                   #count (atom.atom 0)
                   #start_turnstile (..semaphore 0)
                   #end_turnstile (..semaphore 0)}))

  (def: (un_block times turnstile)
    (-> Nat Semaphore (Async Any))
    (loop [step 0]
      (if (n.< times step)
        (do async.monad
          [outcome (..signal turnstile)]
          (recur (inc step)))
        (\ async.monad in []))))

  (template [<phase> <update> <goal> <turnstile>]
    [(def: (<phase> (^:representation barrier))
       (-> Barrier (Async Any))
       (do async.monad
         [#let [limit (refinement.un_refine (get@ #limit barrier))
                goal <goal>
                [_ count] (io.run (atom.update <update> (get@ #count barrier)))
                reached? (n.= goal count)]]
         (if reached?
           (..un_block (dec limit) (get@ <turnstile> barrier))
           (..wait (get@ <turnstile> barrier)))))]

    [start inc limit #start_turnstile]
    [end   dec 0     #end_turnstile]
    )

  (def: #export (block barrier)
    {#.doc (doc "Wait on a barrier until all processes have arrived and met the barrier's limit.")}
    (-> Barrier (Async Any))
    (do async.monad
      [_ (..start barrier)]
      (..end barrier)))
  )