6 val enque
: 'a t
* 'a
-> unit
7 val deque
: 'a t
-> 'a option
10 datatype 'a t
= T
of {front
: 'a list ref
, back
: 'a list ref
}
12 fun new () = T
{front
= ref
[], back
= ref
[]}
14 fun enque (T
{back
, ...}, x
) = back
:= x
:: !back
16 fun deque (T
{front
, back
}) =
20 | l
=> let val l
= rev l
22 [] => raise Fail
"deque"
23 | x
:: l
=> (back
:= []; front
:= l
; SOME x
)
25 | x
:: l
=> (front
:= l
; SOME x
)
32 val spawn
: (unit
-> unit
) -> unit
33 val yield
: unit
-> unit
39 val topLevel
: Thread
.Runnable
.t option ref
= ref NONE
42 val threads
: Thread
.Runnable
.t Queue
.t
= Queue
.new ()
44 fun ready (t
: Thread
.Runnable
.t
) : unit
=
45 Queue
.enque(threads
, t
)
46 fun next () : Thread
.Runnable
.t
=
47 case Queue
.deque threads
of
48 NONE
=> valOf (!topLevel
)
52 fun 'a
exit (): 'a
= switch (fn _
=> next ())
54 fun new (f
: unit
-> unit
): Thread
.Runnable
.t
=
56 (Thread
.new (fn () => ((f () handle _
=> exit ())
60 fun schedule t
= (ready t
; next ())
62 fun yield (): unit
= switch (fn t
=> schedule (Thread
.prepare (t
, ())))
64 val spawn
= ready
o new
68 (topLevel
:= SOME (Thread
.prepare (t
, ()))
75 | n
=> (print(concat
[Int.toString n
, "\n"])
81 | n
=> (Thread
.spawn (fn () => loop n
); loop
' (n
- 2))
83 val _
= Thread
.spawn (fn () => loop
' 10)
87 val _
= print
"success\n"