Debian Codegraph @

doc/guide/src/ConcurrentMLImplementation.adoc

raw
1 = ConcurrentMLImplementation
2
3 Here are some notes on MLton's implementation of <<ConcurrentML#>>.
4
5 Concurrent ML was originally implemented for SML/NJ. It was ported to
6 MLton in the summer of 2004. The main difference between the
7 implementations is that SML/NJ uses continuations to implement CML
8 threads, while MLton uses its underlying <<MLtonThread#,thread>>
9 package. Presently, MLton's threads are a little more heavyweight
10 than SML/NJ's continuations, but it's pretty clear that there is some
11 fat there that could be trimmed.
12
13 The implementation of CML in SML/NJ is built upon the first-class
14 continuations of the `SMLofNJ.Cont` module.
15 [source,sml]
16 ----
17 type 'a cont
18 val callcc: ('a cont -> 'a) -> 'a
19 val isolate: ('a -> unit) -> 'a cont
20 val throw: 'a cont -> 'a -> 'b
21 ----
22
23 The implementation of CML in MLton is built upon the first-class
24 threads of the <<MLtonThread#>> module.
25 [source,sml]
26 ----
27 type 'a t
28 val new: ('a -> unit) -> 'a t
29 val prepare: 'a t * 'a -> Runnable.t
30 val switch: ('a t -> Runnable.t) -> 'a
31 ----
32
33 The port is relatively straightforward, because CML always throws to a
34 continuation at most once. Hence, an "abstract" implementation of
35 CML could be built upon first-class one-shot continuations, which map
36 equally well to SML/NJ's continuations and MLton's threads.
37
38 The "essence" of the port is to transform:
39 ----
40 callcc (fn k => ... throw k' v')
41 ----
42 {empty}to
43 ----
44 switch (fn t => ... prepare (t', v'))
45 ----
46 which suffices for the vast majority of the CML implementation.
47
48 There was only one complicated transformation: blocking multiple base
49 events. In SML/NJ CML, the representation of base events is given by:
50 [source,sml]
51 ----
52 datatype 'a event_status
53 = ENABLED of {prio: int, doFn: unit -> 'a}
54 | BLOCKED of {
55 transId: trans_id ref,
56 cleanUp: unit -> unit,
57 next: unit -> unit
58 } -> 'a
59 type 'a base_evt = unit -> 'a event_status
60 ----
61
62 When synchronizing on a set of base events, which are all blocked, we
63 must invoke each `BLOCKED` function with the same `transId` and
64 `cleanUp` (the `transId` is (checked and) set to `CANCEL` by the
65 `cleanUp` function, which is invoked by the first enabled event; this
66 "fizzles" every other event in the synchronization group that later
67 becomes enabled). However, each `BLOCKED` function is implemented by
68 a callcc, so that when the event is enabled, it throws back to the
69 point of synchronization. Hence, the next function (which doesn't
70 return) is invoked by the `BLOCKED` function to escape the callcc and
71 continue in the thread performing the synchronization. In SML/NJ this
72 is implemented as follows:
73 [source,sml]
74 ----
75 fun ext ([], blockFns) = callcc (fn k => let
76 val throw = throw k
77 val (transId, setFlg) = mkFlg()
78 fun log [] = S.atomicDispatch ()
79 | log (blockFn:: r) =
80 throw (blockFn {
81 transId = transId,
82 cleanUp = setFlg,
83 next = fn () => log r
84 })
85 in
86 log blockFns; error "[log]"
87 end)
88 ----
89 (Note that `S.atomicDispatch` invokes the continuation of the next
90 continuation on the ready queue.) This doesn't map well to the MLton
91 thread model. Although it follows the
92 ----
93 callcc (fn k => ... throw k v)
94 ----
95 model, the fact that `blockFn` will also attempt to do
96 ----
97 callcc (fn k' => ... next ())
98 ----
99 means that the naive transformation will result in nested `switch`-es.
100
101 We need to think a little more about what this code is trying to do.
102 Essentially, each `blockFn` wants to capture this continuation, hold
103 on to it until the event is enabled, and continue with next; when the
104 event is enabled, before invoking the continuation and returning to
105 the synchronization point, the `cleanUp` and other event specific
106 operations are performed.
107
108 To accomplish the same effect in the MLton thread implementation, we
109 have the following:
110 [source,sml]
111 ----
112 datatype 'a status =
113 ENABLED of {prio: int, doitFn: unit -> 'a}
114 | BLOCKED of {transId: trans_id,
115 cleanUp: unit -> unit,
116 next: unit -> rdy_thread} -> 'a
117
118 type 'a base = unit -> 'a status
119
120 fun ext ([], blockFns): 'a =
121 S.atomicSwitch
122 (fn (t: 'a S.thread) =>
123 let
124 val (transId, cleanUp) = TransID.mkFlg ()
125 fun log blockFns: S.rdy_thread =
126 case blockFns of
127 [] => (S.atomicEnd (); S.next ())
128 | blockFn::blockFns =>
129 let
130 val () = S.atomicBegin ()
131 in
132 (S.prep o S.new)
133 (fn _ => fn () =>
134 let
135 val () = S.atomicBegin ()
136 val x = blockFn {transId = transId,
137 cleanUp = cleanUp,
138 next = fn () => log blockFns}
139 in S.switch(fn _ => S.prepVal (t, x))
140 end)
141 end
142 in
143 log blockFns
144 end)
145 ----
146
147 To avoid the nested `switch`-es, I run the `blockFn` in it's own
148 thread, whose only purpose is to return to the synchronization point.
149 This corresponds to the `throw (blockFn {...})` in the SML/NJ
150 implementation. I'm worried that this implementation might be a
151 little expensive, starting a new thread for each blocked event (when
152 there are only multiple blocked events in a synchronization group).
153 But, I don't see another way of implementing this behavior in the
154 MLton thread model.
155
156 Note that another way of thinking about what is going on is to
157 consider each `blockFn` as prepending a different set of actions to
158 the thread `t`. It might be possible to give a
159 `MLton.Thread.unsafePrepend`.
160 [source,sml]
161 ----
162 fun unsafePrepend (T r: 'a t, f: 'b -> 'a): 'b t =
163 let
164 val t =
165 case !r of
166 Dead => raise Fail "prepend to a Dead thread"
167 | New g => New (g o f)
168 | Paused (g, t) => Paused (fn h => g (f o h), t)
169 in (* r := Dead; *)
170 T (ref t)
171 end
172 ----
173 I have commented out the `r := Dead`, which would allow multiple
174 prepends to the same thread (i.e., not destroying the original thread
175 in the process). Of course, only one of the threads could be run: if
176 the original thread were in the `Paused` state, then multiple threads
177 would share the underlying runtime/primitive thread. Now, this
178 matches the "one-shot" nature of CML continuations/threads, but I'm
179 not comfortable with extending `MLton.Thread` with such an unsafe
180 operation.
181
182 Other than this complication with blocking multiple base events, the
183 port was quite routine. (As a very pleasant surprise, the CML
184 implementation in SML/NJ doesn't use any SML/NJ-isms.) There is a
185 slight difference in the way in which critical sections are handled in
186 SML/NJ and MLton; since `MLton.Thread.switch` _always_ leaves a
187 critical section, it is sometimes necessary to add additional
188 `atomicBegin`-s/`atomicEnd`-s to ensure that we remain in a critical
189 section after a thread switch.
190
191 While looking at virtually every file in the core CML implementation,
192 I took the liberty of simplifying things where it seemed possible; in
193 terms of style, the implementation is about half-way between Reppy's
194 original and MLton's.
195
196 Some changes of note:
197
198 * `util/` contains all pertinent data-structures: (functional and
199 imperative) queues, (functional) priority queues. Hence, it should be
200 easier to switch in more efficient or real-time implementations.
201
202 * `core-cml/scheduler.sml`: in both implementations, this is where
203 most of the interesting action takes place. I've made the connection
204 between `MLton.Thread.t`-s and `ThreadId.thread_id`-s more abstract
205 than it is in the SML/NJ implementation, and encapsulated all of the
206 `MLton.Thread` operations in this module.
207
208 * eliminated all of the "by hand" inlining
209
210
211 == Future Extensions
212
213 The CML documentation says the following:
214 ____
215
216 ----
217 CML.joinEvt: thread_id -> unit event
218 ----
219
220 * `joinEvt tid`
221 +
222 creates an event value for synchronizing on the termination of the
223 thread with the ID tid. There are three ways that a thread may
224 terminate: the function that was passed to spawn (or spawnc) may
225 return; it may call the exit function, or it may have an uncaught
226 exception. Note that `joinEvt` does not distinguish between these
227 cases; it also does not become enabled if the named thread deadlocks
228 (even if it is garbage collected).
229 ____
230
231 I believe that the `MLton.Finalizable` might be able to relax that
232 last restriction. Upon the creation of a `'a Scheduler.thread`, we
233 could attach a finalizer to the underlying `'a MLton.Thread.t` that
234 enables the `joinEvt` (in the associated `ThreadID.thread_id`) when
235 the `'a MLton.Thread.t` becomes unreachable.
236
237 I don't know why CML doesn't have
238 ----
239 CML.kill: thread_id -> unit
240 ----
241 which has a fairly simple implementation -- setting a kill flag in the
242 `thread_id` and adjusting the scheduler to discard any killed threads
243 that it takes off the ready queue. The fairness of the scheduler
244 ensures that a killed thread will eventually be discarded. The
245 semantics are little murky for blocked threads that are killed,
246 though. For example, consider a thread blocked on `SyncVar.mTake mv`
247 and a thread blocked on `SyncVar.mGet mv`. If the first thread is
248 killed while blocked, and a third thread does `SyncVar.mPut (mv, x)`,
249 then we might expect that we'll enable the second thread, and never
250 the first. But, when only the ready queue is able to discard killed
251 threads, then the `SyncVar.mPut` could enable the first thread
252 (putting it on the ready queue, from which it will be discarded) and
253 leave the second thread blocked. We could solve this by adjusting the
254 `TransID.trans_id types` and the "cleaner" functions to look for both
255 canceled transactions and transactions on killed threads.
256
257 John Reppy says that <<References#MarlowEtAl01,MarlowEtAl01>> and <<References#FlattFindler04,FlattFindler04>>
258 explain why `CML.kill` would be a bad idea.
259
260 Between `CML.timeOutEvt` and `CML.kill`, one could give an efficient
261 solution to the recent `comp.lang.ml` post about terminating a
262 function that doesn't complete in a given time.
263 [source,sml]
264 ----
265 fun timeOut (f: unit -> 'a, t: Time.time): 'a option =
266 let
267 val iv = SyncVar.iVar ()
268 val tid = CML.spawn (fn () => SyncVar.iPut (iv, f ()))
269 in
270 CML.select
271 [CML.wrap (CML.timeOutEvt t, fn () => (CML.kill tid; NONE)),
272 CML.wrap (SyncVar.iGetEvt iv, fn x => SOME x)]
273 end
274 ----
275
276
277 == Space Safety
278
279 There are some CML related posts on the MLton mailing list:
280
281 * http://www.mlton.org/pipermail/mlton/2004-May/
282
283 that discuss concerns that SML/NJ's implementation is not space
284 efficient, because multi-shot continuations can be held indefinitely
285 on event queues. MLton is better off because of the one-shot nature
286 -- when an event enables a thread, all other copies of the thread
287 waiting in other event queues get turned into dead threads (of zero
288 size).