Repository navigation
Expand file tree
/
Copy pathAsyncOneShot.fs
More file actions
213 lines (183 loc) · 8.7 KB
/
Copy pathAsyncOneShot.fs
File metadata and controls
213 lines (183 loc) · 8.7 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/// <summary><c>Async.FromContinuations</c> が渡す <c>(ok, err, cancel)</c> を、そのまま 1 回限りの継続として使う。</summary>
/// <remarks>
/// <para>
/// F# の <c>Async</c> は、もともと継続の仕組みを持っている。<c>ok</c> が OCaml の <c>continue</c>、
/// <c>err</c> が <c>discontinue</c> に当たり、2 回目の呼び出しは FSharp.Core が検査して例外にする。
/// FSharp.Core だけで書け、タスクごとにスレッドを消費しない。その代わり計算は <c>async { }</c> で色付けされる。
/// </para>
/// <para>
/// 操作は型で探さず、<see cref="T:EffectSystem.Samples.AsyncOneShot.Scheduler"/> のメソッドとして直接呼ぶ。
/// スコープの仕組みは能力渡しと同じで、スケジューラーを持っていなければ操作を呼べない。
/// </para>
/// </remarks>
/// <category index="4">発展</category>
module EffectSystem.Samples.AsyncOneShot
open System
open System.Collections.Generic
open System.Threading
open EffectSystem.Samples.Effects
/// <summary>取り出した継続。OCaml の <c>continue</c> と <c>discontinue</c> の組に当たる。</summary>
/// <typeparam name="'a">再開するときに渡す値の型。</typeparam>
type Continuation<'a> =
{ /// <summary>値で再開する。</summary>
Resume: 'a -> unit
/// <summary>例外で再開する。中断している位置で例外が発生し、<c>finally</c> が走る。</summary>
Discontinue: exn -> unit }
/// <summary>止まっている計算の状態。<c>Interlocked</c> で 1 度だけ変える。</summary>
module private CaptureState =
/// <summary>再開も中断もまだ届いていない。</summary>
[<Literal>]
let Parked = 0
/// <summary>再開が先に届いた。</summary>
[<Literal>]
let Resumed = 1
/// <summary>中断が先に届いた。</summary>
[<Literal>]
let Cancelled = 2
/// <summary>中断して継続を取り出す。2 回目の再開は FSharp.Core が <c>InvalidOperationException</c> にする。</summary>
/// <remarks>
/// <para>
/// <c>FromContinuations</c> の <c>cancel</c> は自動では呼ばれない。呼ばなければ、止まっている計算は <c>Cancel</c> に応じず、<c>finally</c> も走らない。
/// そこでトークンに登録して、自分で呼ぶ。
/// </para>
/// <para>
/// 中断が先に届いた継続を後から再開しても、計算はもう終わっているので何も起きない。
/// スケジューラーのキューに残った再開は、そのまま呼んでよい。
/// </para>
/// </remarks>
/// <param name="f">継続を受け取る関数。保存しておいて後で再開してよい。</param>
let capture (f: Continuation<'a> -> unit) : Async<'a> =
async {
let! token = Async.CancellationToken
return!
Async.FromContinuations(fun (ok, err, cancel) ->
let state = ref CaptureState.Parked
let registration = ref Unchecked.defaultof<CancellationTokenRegistration>
// 2 回目の再開は ok と err がそのまま拒否する。
let resumeWith (continuation: 'x -> unit) (x: 'x) =
if Interlocked.CompareExchange(&state.contents, CaptureState.Resumed, CaptureState.Parked) <> CaptureState.Cancelled then
registration.Value.Unregister() |> ignore
continuation x
registration.Value <-
token.Register(fun () ->
if Interlocked.CompareExchange(&state.contents, CaptureState.Cancelled, CaptureState.Parked) = CaptureState.Parked then
cancel (OperationCanceledException token))
if state.Value = CaptureState.Parked then
f { Resume = resumeWith ok; Discontinue = resumeWith err })
}
/// <summary>交換の相手がいないまま止まったタスクへ届ける例外。</summary>
exception ImproperSynchronization
/// <summary>マニュアル 24.3 のラウンドロビンのスケジューラー。<c>perform</c> の代わりにメソッドを直接呼ぶ。</summary>
/// <remarks>
/// キューには継続の再開を入れる。止まったタスクは継続として保存されているだけで、スレッドを占有しない。
/// </remarks>
/// <param name="out">タスクの例外の出力先。</param>
type Scheduler(out: Log) =
let runQ = Queue<unit -> unit>()
let mutable exchanger: (int * Continuation<int>) option = None
let start (task: Async<unit>) =
Async.StartWithContinuations(task, ignore, (fun e -> out (e.GetType().Name)), ignore)
/// <summary>他のタスクへ実行を譲る。</summary>
member _.Yield() : Async<unit> =
capture (fun k -> runQ.Enqueue(fun () -> k.Resume()))
/// <summary>新しいタスクをすぐに起動し、今のタスクをキューへ入れる。</summary>
member _.Fork(task: Async<unit>) : Async<unit> =
capture (fun k ->
runQ.Enqueue(fun () -> k.Resume())
start task)
/// <summary>他のタスクと値を交換する。相手がいなければ止まって待つ。</summary>
member _.Xchg(n: int) : Async<int> =
capture (fun k ->
match exchanger with
| Some(n', k') ->
exchanger <- None
runQ.Enqueue(fun () -> k'.Resume n)
k.Resume n'
| None -> exchanger <- Some(n, k))
/// <summary>キューが空になるまでタスクを動かす。最後まで相手のいないタスクには例外を届ける。</summary>
/// <remarks>
/// <c>Async</c> の継続は、<c>Async</c> の実行中のスレッドから呼ぶとスレッドプールへ回されて順序が崩れる。
/// そうならないようキューを専用のスレッドで回す。
/// </remarks>
member _.Run(main: Async<unit>) : unit =
let loop () =
start main
while runQ.Count > 0 || exchanger.IsSome do
if runQ.Count > 0 then
runQ.Dequeue () ()
else
let (_, k) = exchanger.Value
exchanger <- None
k.Discontinue ImproperSynchronization
let thread = Thread(loop)
thread.Start()
thread.Join()
/// <summary>2 つのタスクが値を交換する。出力の順序はマニュアル 24.3 と同じである。</summary>
/// <param name="out">出力先。</param>
let userLevelThreads (out: Log) : unit =
let s = Scheduler(out)
s.Run(
async {
do!
s.Fork(
async {
out "[t1] Sending 0"
let! v = s.Xchg 0
out $"[t1] received {v}"
}
)
do!
s.Fork(
async {
out "[t2] Sending 1"
let! v = s.Xchg 1
out $"[t2] received {v}"
}
)
}
)
/// <summary>相手のいない <c>Xchg</c> で止まったタスクにも、例外での再開によって <c>finally</c> が走る。</summary>
/// <param name="out">出力先。</param>
let resumingWithAnException (out: Log) : unit =
let s = Scheduler(out)
s.Run(
async {
try
out "open"
let! v = s.Xchg 0
out $"received {v}"
finally
out "close"
}
)
/// <summary>継続を 2 回呼ぶ。FSharp.Core の検査で <c>InvalidOperationException</c> になる。</summary>
let resumeTwice () : unit =
let saved = ref None
Async.StartImmediate(capture (fun k -> saved.Value <- Some k))
let k: Continuation<unit> = saved.Value.Value
k.Resume()
k.Resume()
/// <summary>止まっている計算を中断すると <c>finally</c> が走る。その後の再開は何も起こさない。</summary>
/// <param name="out">出力先。</param>
let cancelWhileParked (out: Log) : unit =
use source = new CancellationTokenSource()
use finished = new ManualResetEventSlim(false)
let saved = ref None
let task =
async {
try
out "parked"
do! capture (fun k -> saved.Value <- Some k)
out "not reached"
finally
out "finally"
}
let onCancelled (_: OperationCanceledException) =
out "cancelled"
finished.Set()
Async.StartWithContinuations(task, ignore, ignore, onCancelled, source.Token)
source.Cancel()
finished.Wait()
let k: Continuation<unit> = saved.Value.Value
k.Resume()
out "resumed after cancel"