aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/thread.lux
blob: 0902501b4199747b488b8a134ff15c8a55f6c0e9 (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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
(.using
 [library
  [lux "*"
   ["@" target]
   ["[0]" ffi]
   [abstract
    ["[0]" monad {"+" do}]]
   [control
    ["[0]" try]
    ["[0]" exception {"+" exception:}]
    ["[0]" io {"+" IO io}]]
   [data
    ["[0]" text]
    [collection
     ["[0]" list]]]
   [math
    [number
     ["n" nat]
     ["f" frac]]]
   [meta
    ["[0]" configuration]]
   [time
    ["[0]" instant]]]]
 [//
  ["[0]" atom {"+" Atom}]])

(with_expansions [<jvm> (these (ffi.import: java/lang/Object
                                 "[1]::[0]")
                               
                               (ffi.import: java/lang/Long
                                 "[1]::[0]")

                               (ffi.import: java/lang/Runtime
                                 "[1]::[0]"
                                 ("static" getRuntime [] java/lang/Runtime)
                                 (availableProcessors [] int))

                               (ffi.import: java/lang/Runnable
                                 "[1]::[0]")

                               (ffi.import: java/util/concurrent/TimeUnit
                                 "[1]::[0]"
                                 ("enum" MILLISECONDS))
                               
                               (ffi.import: java/util/concurrent/Executor
                                 "[1]::[0]"
                                 (execute [java/lang/Runnable] "io" void))

                               (ffi.import: (java/util/concurrent/ScheduledFuture a)
                                 "[1]::[0]")

                               (ffi.import: java/util/concurrent/ScheduledThreadPoolExecutor
                                 "[1]::[0]"
                                 (new [int])
                                 (schedule [java/lang/Runnable long java/util/concurrent/TimeUnit] "io" (java/util/concurrent/ScheduledFuture java/lang/Object))))]
  (for @.old (these <jvm>)
       @.jvm (these <jvm>)

       @.js
       (these (ffi.import: (setTimeout [ffi.Function ffi.Number] "io" Any)))

       @.python
       (ffi.import: threading/Timer
         "[1]::[0]"
         (new [ffi.Float ffi.Function])
         (start [] "io" "?" Any))
       
       ... Default
       (type: Thread
         (Record
          [#creation Nat
           #delay Nat
           #action (IO Any)]))
       ))

(def: .public parallelism
  Nat
  (with_expansions [<default> 1
                    <jvm> (<| (configuration.for ["lua_compiler?" ""]
                                                 ... TODO: Remove this when Rembulan is no longer being used.
                                                 <default>)
                              (|> (java/lang/Runtime::getRuntime)
                                  (java/lang/Runtime::availableProcessors)
                                  ffi.of_int
                                  .nat))]
    (for @.old <jvm>
         @.jvm <jvm>
         ... Default
         <default>)))

(with_expansions [<jvm> (these (def: runner
                                 java/util/concurrent/ScheduledThreadPoolExecutor
                                 (|> ..parallelism
                                     .int
                                     ffi.as_int
                                     java/util/concurrent/ScheduledThreadPoolExecutor::new)))]
  (for @.old <jvm>
       @.jvm <jvm>
       @.js (these)
       @.python (these)
       
       ... Default
       (these (def: started?
                (Atom Bit)
                (atom.atom false))
              (def: runner
                (Atom (List Thread))
                (atom.atom (list))))))

(def: (execute! action)
  (-> (IO Any) Any)
  (case (try (io.run! action))
    {try.#Failure error}
    (exec
      ("lux io log" (all "lux text concat"
                         "ERROR DURING THREAD EXECUTION:" text.new_line
                         error))
      [])
    
    {try.#Success _}
    []))

(def: .public (schedule! milli_seconds action)
  (-> Nat (IO Any) (IO Any))
  (with_expansions [<jvm> (let [runnable (ffi.object [] [java/lang/Runnable]
                                           []
                                           (java/lang/Runnable [] (run self []) void
                                                               (..execute! action)))]
                            (case milli_seconds
                              0 (java/util/concurrent/Executor::execute runnable runner)
                              _ (java/util/concurrent/ScheduledThreadPoolExecutor::schedule runnable (.int milli_seconds) java/util/concurrent/TimeUnit::MILLISECONDS
                                                                                            runner)))]
    (for @.old <jvm>
         @.jvm <jvm>

         @.js
         (..setTimeout (ffi.function (_ []) Any (..execute! action))
                       (n.frac milli_seconds))

         @.python
         (do io.monad
           [_ (|> (ffi.function (_ []) Any (..execute! action))
                  (threading/Timer::new (|> milli_seconds n.frac (f./ +1,000.0)))
                  threading/Timer::start)]
           (in []))
         
         ... Default
         (do [! io.monad]
           [now (# ! each (|>> instant.millis .nat) instant.now)
            _ (atom.update! (|>> {.#Item [#creation now
                                          #delay milli_seconds
                                          #action action]})
                            ..runner)]
           (in [])))))

(for @.old (these)
     @.jvm (these)
     @.js (these)
     @.python (these)
     
     ... Default
     (these (exception: .public cannot_continue_running_threads)

            ... https://en.wikipedia.org/wiki/Event_loop
            ... Starts the event-loop.
            (def: .public run!
              (IO Any)
              (do [! io.monad]
                [started? (atom.read! ..started?)]
                (if started?
                  (in [])
                  (do !
                    [_ (atom.write! true ..started?)]
                    (loop (again [_ []])
                      (do !
                        [threads (atom.read! ..runner)]
                        (case threads
                          ... And... we're done!
                          {.#End}
                          (in [])

                          _
                          (do !
                            [now (# ! each (|>> instant.millis .nat) instant.now)
                             .let [[ready pending] (list.partition (function (_ thread)
                                                                     (|> (the #creation thread)
                                                                         (n.+ (the #delay thread))
                                                                         (n.<= now)))
                                                                   threads)]
                             swapped? (atom.compare_and_swap! threads pending ..runner)]
                            (if swapped?
                              (do !
                                [_ (monad.each ! (|>> (the #action) ..execute! io.io) ready)]
                                (again []))
                              (panic! (exception.error ..cannot_continue_running_threads []))))
                          )))))))
            ))