Debian Codegraph @

doc/guide/src/MLtonThread.adoc

raw
1 = MLtonThread
2
3 [source,sml]
4 ----
5 signature MLTON_THREAD =
6 sig
7 structure AtomicState:
8 sig
9 datatype t = NonAtomic | Atomic of int
10 end
11
12 val atomically: (unit -> 'a) -> 'a
13 val atomicBegin: unit -> unit
14 val atomicEnd: unit -> unit
15 val atomicState: unit -> AtomicState.t
16
17 structure Runnable:
18 sig
19 type t
20 end
21
22 type 'a t
23
24 val atomicSwitch: ('a t -> Runnable.t) -> 'a
25 val new: ('a -> unit) -> 'a t
26 val prepend: 'a t * ('b -> 'a) -> 'b t
27 val prepare: 'a t * 'a -> Runnable.t
28 val switch: ('a t -> Runnable.t) -> 'a
29 end
30 ----
31
32 `MLton.Thread` provides access to MLton's user-level thread
33 implementation (i.e. not OS-level threads). Threads are lightweight
34 data structures that represent a paused computation. Runnable threads
35 are threads that will begin or continue computing when `switch`-ed to.
36 `MLton.Thread` does not include a default scheduling mechanism, but it
37 can be used to implement both preemptive and non-preemptive threads.
38
39 * `type AtomicState.t`
40 +
41 the type of atomic states.
42
43
44 * `atomically f`
45 +
46 runs `f` in a critical section.
47
48 * `atomicBegin ()`
49 +
50 begins a critical section.
51
52 * `atomicEnd ()`
53 +
54 ends a critical section.
55
56 * `atomicState ()`
57 +
58 returns the current atomic state.
59
60 * `type Runnable.t`
61 +
62 the type of threads that can be resumed.
63
64 * `type 'a t`
65 +
66 the type of threads that expect a value of type `'a`.
67
68 * `atomicSwitch f`
69 +
70 like `switch`, but assumes an atomic calling context. Upon
71 `switch`-ing back to the current thread, an implicit `atomicEnd` is
72 performed.
73
74 * `new f`
75 +
76 creates a new thread that, when run, applies `f` to the value given to
77 the thread. `f` must terminate by `switch`ing to another thread or
78 exiting the process.
79
80 * `prepend (t, f)`
81 +
82 creates a new thread (destroying `t` in the process) that first
83 applies `f` to the value given to the thread and then continues with
84 `t`. This is a constant time operation.
85
86 * `prepare (t, v)`
87 +
88 prepares a new runnable thread (destroying `t` in the process) that
89 will evaluate `t` on `v`.
90
91 * `switch f`
92 +
93 applies `f` to the current thread to get `rt`, and then start running
94 thread `rt`. It is an error for `f` to perform another `switch`. `f`
95 is guaranteed to run atomically.
96
97
98 == Example of non-preemptive threads
99
100 [source,sml]
101 ----
102 include::https://raw.github.com/MLton/mlton/master/doc/examples/thread/non-preemptive-threads.sml[indent=0]
103 ----
104
105
106 == Example of preemptive threads
107
108 [source,sml]
109 ----
110 include::https://raw.github.com/MLton/mlton/master/doc/examples/thread/preemptive-threads.sml[indent=0]
111 ----