Source file CCPool.ml
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
(** {1 Thread Pool, and Futures} *)
type +'a state = Done of 'a | Waiting | Failed of exn
module type PARAM = sig
val max_size : int
(** Maximum number of threads in the pool *)
end
exception Stopped
(** {2 Thread pool} *)
module Make (P : PARAM) = struct
type job =
| Job1 : ('a -> _) * 'a -> job
| Job2 : ('a -> 'b -> _) * 'a * 'b -> job
| Job3 : ('a -> 'b -> 'c -> _) * 'a * 'b * 'c -> job
| Job4 : ('a -> 'b -> 'c -> 'd -> _) * 'a * 'b * 'c * 'd -> job
type t = {
mutable stop: bool;
mutable exn_handler: exn -> unit;
mutex: Mutex.t;
cond: Condition.t;
jobs: job Queue.t;
mutable cur_size: int;
mutable cur_idle: int;
}
(** Dynamic, growable thread pool *)
let nop_ _ = ()
let pool =
{
stop = false;
exn_handler = nop_;
cond = Condition.create ();
cur_size = 0;
cur_idle = 0;
jobs = Queue.create ();
mutex = Mutex.create ();
}
let set_exn_handler f = pool.exn_handler <- f
let[@inline] with_lock_ t f =
Mutex.lock t.mutex;
try
let x = f t in
Mutex.unlock t.mutex;
x
with e ->
Mutex.unlock t.mutex;
raise e
let incr_size_ p = p.cur_size <- p.cur_size + 1
let decr_size_ p = p.cur_size <- p.cur_size - 1
let incr_idle_ p = p.cur_idle <- p.cur_idle + 1
let decr_idle_ p = p.cur_idle <- p.cur_idle - 1
type command =
| Process of job
| Wait
| Die
let get_next_ pool =
if pool.stop then
Die
else (
match Queue.take pool.jobs with
| exception Queue.Empty ->
if pool.cur_idle > 0 then
Die
else
Wait
| job -> Process job
)
let[@inline] can_start_thread_ p = p.cur_size < P.max_size
let rec serve pool =
assert (pool.cur_size <= P.max_size);
assert (pool.cur_size > 0);
Mutex.lock pool.mutex;
let cmd = get_next_ pool in
maybe_start_runner_ pool;
run_cmd pool cmd
and run_cmd pool = function
| Die ->
decr_size_ pool;
Mutex.unlock pool.mutex;
()
| Wait ->
incr_idle_ pool;
Condition.wait pool.cond pool.mutex;
decr_idle_ pool;
Mutex.unlock pool.mutex;
serve pool
| Process job ->
Mutex.unlock pool.mutex;
run_job pool job
and run_job pool job =
match job with
| Job1 (f, x) ->
(try ignore (f x) with e -> pool.exn_handler e);
serve pool
| Job2 (f, x, y) ->
(try ignore (f x y) with e -> pool.exn_handler e);
serve pool
| Job3 (f, x, y, z) ->
(try ignore (f x y z) with e -> pool.exn_handler e);
serve pool
| Job4 (f, x, y, z, w) ->
(try ignore (f x y z w) with e -> pool.exn_handler e);
serve pool
and maybe_start_runner_ pool : unit =
if (not (Queue.is_empty pool.jobs)) && can_start_thread_ pool then (
let job' = Queue.pop pool.jobs in
launch_worker_on_ pool job'
)
and[@inline] launch_worker_on_ pool job =
incr_size_ pool;
ignore (Thread.create (run_job pool) job)
let run_job job =
with_lock_ pool (fun pool ->
if pool.stop then raise Stopped;
if
Queue.is_empty pool.jobs && can_start_thread_ pool
&& pool.cur_idle = 0
then
launch_worker_on_ pool job
else if pool.cur_idle > 0 then (
Queue.push job pool.jobs;
Condition.broadcast pool.cond
) else (
Queue.push job pool.jobs;
if can_start_thread_ pool then (
let job' = Queue.pop pool.jobs in
launch_worker_on_ pool job'
)
))
let run1 f x = run_job (Job1 (f, x))
let run f = run1 f ()
let run2 f x y = run_job (Job2 (f, x, y))
let run3 f x y z = run_job (Job3 (f, x, y, z))
let run4 f x y z w = run_job (Job4 (f, x, y, z, w))
let active () = not pool.stop
let stop () =
with_lock_ pool (fun p ->
p.stop <- true;
Queue.clear p.jobs;
Condition.broadcast p.cond )
let () = Gc.finalise (fun _ -> stop ()) pool
(** {6 Futures} *)
module Fut = struct
type 'a handler = 'a state -> unit
type 'a cell = {
mutable state: 'a state;
mutable handlers: 'a handler list;
f_mutex: Mutex.t;
condition: Condition.t;
}
(** A proper future, with a delayed computation *)
(** A future value of type 'a *)
type 'a t = Return of 'a | FailNow of exn | Run of 'a cell
type 'a future = 'a t
(** {2 Basic Future functions} *)
let return x = Return x
let fail e = FailNow e
let create_cell () =
{
state = Waiting;
handlers = [];
f_mutex = Mutex.create ();
condition = Condition.create ();
}
let with_lock_ cell f =
Mutex.lock cell.f_mutex;
try
let x = f cell in
Mutex.unlock cell.f_mutex;
x
with e ->
Mutex.unlock cell.f_mutex;
raise e
let set_done_ cell x =
with_lock_ cell (fun cell ->
match cell.state with
| Waiting ->
cell.state <- Done x;
Condition.broadcast cell.condition;
List.iter
(fun f -> try f cell.state with e -> pool.exn_handler e)
cell.handlers
| _ -> assert false)
let set_fail_ cell e =
with_lock_ cell (fun cell ->
match cell.state with
| Waiting ->
cell.state <- Failed e;
Condition.broadcast cell.condition;
List.iter
(fun f -> try f cell.state with e -> pool.exn_handler e)
cell.handlers
| _ -> assert false)
let run_and_set1 cell f x =
try
let y = f x in
set_done_ cell y
with e -> set_fail_ cell e
let run_and_set2 cell f x y =
try
let z = f x y in
set_done_ cell z
with e -> set_fail_ cell e
let make1 f x =
let cell = create_cell () in
run3 run_and_set1 cell f x;
Run cell
let make f = make1 f ()
let make2 f x y =
let cell = create_cell () in
run4 run_and_set2 cell f x y;
Run cell
let get = function
| Return x -> x
| FailNow e -> raise e
| Run cell ->
let rec get_ cell =
match cell.state with
| Waiting ->
Condition.wait cell.condition cell.f_mutex;
get_ cell
| Done x -> x
| Failed e -> raise e
in
with_lock_ cell get_
let get_nolock_ = function
| Return x | Run { state = Done x; _ } -> x
| FailNow _ | Run { state = Failed _ | Waiting; _ } -> assert false
let state = function
| Return x -> Done x
| FailNow e -> Failed e
| Run cell -> with_lock_ cell (fun cell -> cell.state)
let is_not_waiting = function
| Waiting -> false
| Failed _ | Done _ -> true
let is_done = function
| Return _ | FailNow _ -> true
| Run cell -> with_lock_ cell (fun c -> is_not_waiting c.state)
(** {2 Combinators *)
let add_handler_ cell f =
with_lock_ cell (fun cell ->
match cell.state with
| Waiting -> cell.handlers <- f :: cell.handlers
| Done _ | Failed _ -> f cell.state)
let on_finish fut k =
match fut with
| Return x -> k (Done x)
| FailNow e -> k (Failed e)
| Run cell -> add_handler_ cell k
let on_success fut k =
on_finish fut (function
| Done x -> k x
| _ -> ())
let on_failure fut k =
on_finish fut (function
| Failed e -> k e
| _ -> ())
let map_cell_ ~async f cell ~into:cell' =
add_handler_ cell (function
| Done x ->
if async then
run3 run_and_set1 cell' f x
else
run_and_set1 cell' f x
| Failed e -> set_fail_ cell' e
| Waiting -> assert false);
Run cell'
let map_ ~async f fut =
match fut with
| Return x ->
if async then
make1 f x
else
Return (f x)
| FailNow e -> FailNow e
| Run cell -> map_cell_ ~async f cell ~into:(create_cell ())
let map f fut = map_ ~async:false f fut
let map_async f fut = map_ ~async:true f fut
let app_ ~async f x =
match f, x with
| Return f, Return x ->
if async then
make1 f x
else
Return (f x)
| FailNow e, _ | _, FailNow e -> FailNow e
| Return f, Run x ->
map_cell_ ~async (fun x -> f x) x ~into:(create_cell ())
| Run f, Return x ->
map_cell_ ~async (fun f -> f x) f ~into:(create_cell ())
| Run f, Run x ->
let cell' = create_cell () in
add_handler_ f (function
| Done f -> ignore (map_cell_ ~async f x ~into:cell')
| Failed e -> set_fail_ cell' e
| Waiting -> assert false);
Run cell'
let app f x = app_ ~async:false f x
let app_async f x = app_ ~async:true f x
let monoid_product f x y =
match x, y with
| Return x, Return y -> Return (f x y)
| FailNow e, _ | _, FailNow e -> FailNow e
| Return x, Run y ->
map_cell_ ~async:false (fun y -> f x y) y ~into:(create_cell ())
| Run x, Return y ->
map_cell_ ~async:false (fun x -> f x y) x ~into:(create_cell ())
| Run x, Run y ->
let cell' = create_cell () in
add_handler_ x (function
| Done x ->
ignore (map_cell_ ~async:false (fun y -> f x y) y ~into:cell')
| Failed e -> set_fail_ cell' e
| Waiting -> assert false);
Run cell'
let flat_map f fut =
match fut with
| Return x -> f x
| FailNow e -> FailNow e
| Run cell ->
let cell' = create_cell () in
add_handler_ cell (function
| Done x ->
let fut' = f x in
on_finish fut' (function
| Done y -> set_done_ cell' y
| Failed e -> set_fail_ cell' e
| Waiting -> assert false)
| Failed e -> set_fail_ cell' e
| Waiting -> assert false);
Run cell'
let and_then fut f = flat_map (fun _ -> f ()) fut
type _ array_or_list =
| A_ : 'a array -> 'a array_or_list
| L_ : 'a list -> 'a array_or_list
let iter_aol : type a. a array_or_list -> (a -> unit) -> unit =
fun aol f ->
match aol with
| A_ a -> Array.iter f a
| L_ l -> List.iter f l
let sequence_ : type a res. a t array_or_list -> (unit -> res) -> res t =
fun aol f ->
let n =
match aol with
| A_ a -> Array.length a
| L_ l -> List.length l
in
assert (n > 0);
let cell = create_cell () in
let n_err = CCLock.create 0 in
let n_ok = CCLock.create 0 in
iter_aol aol (fun fut ->
on_finish fut (function
| Failed e ->
let x = CCLock.incr_then_get n_err in
if x = 1 then set_fail_ cell e
| Done _ ->
let x = CCLock.incr_then_get n_ok in
if x = n then (
let res = f () in
set_done_ cell res
)
| Waiting -> assert false));
Run cell
let sequence_a a =
match a with
| [||] -> return [||]
| [| x |] -> map (fun x -> [| x |]) x
| _ -> sequence_ (A_ a) (fun () -> Array.map get_nolock_ a)
let map_a f a = sequence_a (Array.map f a)
let sequence_l l =
match l with
| [] -> return []
| _ :: _ ->
let l = List.rev l in
sequence_ (L_ l) (fun () -> List.rev_map get_nolock_ l)
let map_l f l =
match l with
| [] -> return []
| _ ->
let l = List.rev_map f l in
sequence_ (L_ l) (fun () -> List.rev_map get_nolock_ l)
let choose_ : type a. a t array_or_list -> a t =
fun aol ->
let cell = create_cell () in
let is_done = CCLock.create false in
iter_aol aol (fun fut ->
on_finish fut (fun res ->
match res with
| Waiting -> assert false
| Done x ->
let was_done = CCLock.get_then_clear is_done in
if not was_done then set_done_ cell x
| Failed e ->
let was_done = CCLock.get_then_clear is_done in
if not was_done then set_fail_ cell e));
Run cell
let choose_a a = choose_ (A_ a)
let choose_l l = choose_ (L_ l)
let sleep time = make1 Thread.delay time
module Infix = struct
let ( >>= ) x f = flat_map f x
let ( >> ) a f = and_then a f
let ( >|= ) a f = map f a
let ( <*> ) = app
[@@@ifge 4.8]
let ( let+ ) = ( >|= )
let ( let* ) = ( >>= )
let[@inline] ( and+ ) a1 a2 = monoid_product (fun x y -> x, y) a1 a2
let ( and* ) = ( and+ )
[@@@endif]
end
include Infix
end
end