1 open Posix
.Signal MLton
.Signal
3 fun for (start
, stop
, f
) =
8 else (f i
; loop (i
+ 1))
18 val enque
: 'a t
* 'a
-> unit
19 val deque
: 'a t
-> 'a option
22 datatype 'a t
= T
of {front
: 'a list ref
, back
: 'a list ref
}
24 fun new () = T
{front
= ref
[], back
= ref
[]}
26 fun enque (T
{back
, ...}, x
) = back
:= x
:: !back
28 fun deque (T
{front
, back
}) =
32 | l
=> let val l
= rev l
34 [] => raise Fail
"deque"
35 | x
:: l
=> (back
:= []; front
:= l
; SOME x
)
37 | x
:: l
=> (front
:= l
; SOME x
)
44 val spawn
: (unit
-> unit
) -> unit
45 val yield
: unit
-> unit
57 open Itimer Signal Thread
59 val topLevel
: Thread
.Runnable
.t option ref
= ref NONE
62 val threads
: Thread
.Runnable
.t Queue
.t
= Queue
.new ()
64 fun ready t
= Queue
.enque (threads
, t
)
65 fun next () : Thread
.Runnable
.t
=
66 case Queue
.deque threads
of
67 NONE
=> valOf (!topLevel
)
71 fun 'a
exit (): 'a
= switch (fn _
=>
75 fun new (f
: unit
-> unit
): Thread
.Runnable
.t
=
77 (Thread
.new (fn () => ((f () handle _
=> exit ())
81 fun schedule t
= (ready t
; next ())
83 fun yield (): unit
= switch (fn t
=> schedule (Thread
.prepare (t
, ())))
85 val spawn
= ready
o new
88 Itimer
.set (Itimer
.Real,
94 (topLevel
:= SOME (Thread
.prepare (t
, ()))
96 (setHandler (alrm
, Handler
.handler schedule
)
97 ; setItimer (Time
.fromMilliseconds
10)))))
98 ; setItimer Time
.zeroTime
99 ; setHandler (alrm
, Handler
.ignore
)
104 datatype t
= T
of {locked
: bool ref
,
105 waiting
: unit Thread
.t Queue
.t
}
108 T
{locked
= ref
false,
109 waiting
= Queue
.new ()}
111 fun lock (T
{locked
, waiting
, ...}) =
114 (Thread
.atomicBegin ()
116 then (Thread
.atomicEnd ()
118 (Queue
.enque (waiting
, t
)
122 ; Thread
.atomicEnd ()))
126 fun safeUnlock (T
{locked
, waiting
, ...}) =
128 ; (case Queue
.deque waiting
of
130 | SOME t
=> ready (Thread
.prepare (t
,()))))
133 (Thread
.atomicBegin ()
135 ; Thread
.atomicEnd ())
141 fun main (name
, args
) =
144 val gotIt
= ref
false
150 val _
= print
"starting\n"
156 then raise Fail
"bug"
158 ; for (0, 100000, fn _
=> ())
168 val _
= main ( CommandLine
.name (), CommandLine
.arguments () )