aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/concurrency/thread.lux
blob: 8c3a273d44dca3c3351dd6559e0c52ae7f4d5221 (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
(.module:
  [library
   [lux #*
    ["@" target]
    ["." ffi]
    [abstract
     ["." monad (#+ do)]]
    [control
     ["." try]
     ["." exception (#+ exception:)]
     ["." io (#+ IO io)]]
    [data
     ["." text]
     [collection
      ["." list]]]
    [math
     [number
      ["n" nat]
      ["f" frac]]]
    [time
     ["." instant]]]]
  [//
   ["." atom (#+ Atom)]])

(with_expansions [<jvm> (as_is (ffi.import: java/lang/Object)

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

                               (ffi.import: java/lang/Runnable)

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

                               (ffi.import: (java/util/concurrent/ScheduledFuture a))

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

        @.js
        (as_is (ffi.import: (setTimeout [ffi.Function ffi.Number] #io Any)))

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

(def: .public parallelism
  {#.doc (doc "How many processes can run in parallel.")}
  Nat
  (with_expansions [<jvm> (|> (java/lang/Runtime::getRuntime)
                              (java/lang/Runtime::availableProcessors)
                              .nat)]
    (for {@.old <jvm>
          @.jvm <jvm>}
         ## Default
         1)))

(with_expansions [<jvm> (as_is (def: runner
                                 java/util/concurrent/ScheduledThreadPoolExecutor
                                 (java/util/concurrent/ScheduledThreadPoolExecutor::new (.int ..parallelism))))]
  (for {@.old <jvm>
        @.jvm <jvm>
        @.js (as_is)
        @.python (as_is)}
       
       ## Default
       (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" ($_ "lux text concat"
                        "ERROR DURING THREAD EXECUTION:" text.new_line
                        error))
      [])
    
    (#try.Success _)
    []))

(def: .public (schedule milli_seconds action)
  {#.doc (doc "Executes an I/O procedure after some milli-seconds.")}
  (-> Nat (IO Any) (IO Any))
  (with_expansions [<jvm> (as_is (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.closure [] (..execute! action))
                         (n.frac milli_seconds)])

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

(for {@.old (as_is)
      @.jvm (as_is)
      @.js (as_is)
      @.python (as_is)}
     
     ## Default
     (as_is (exception: .public cannot_continue_running_threads)

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

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