Skip to content

Commit 15e4872

Browse files
committed
feat apool: add init_size option for create
1 parent abdedee commit 15e4872

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

src/core/apool.ml

+18-7
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,33 @@ type 'a t = {
1111
items: 'a list_ A.t;
1212
}
1313

14-
let create ?(clear = ignore) ~mk_item ?(max_size = 512) () : _ t =
15-
{ mk_item; clear; max_size; items = A.make Nil }
14+
let[@inline] size_ = function
15+
| Cons (sz, _, _) -> sz
16+
| Nil -> 0
17+
18+
let create ?(clear = ignore) ~mk_item ?(init_size = 0) ?(max_size = 512) () :
19+
_ t =
20+
let@ _sp = Trace.with_span ~__FILE__ ~__LINE__ "apool.create" in
21+
if max_size < init_size then invalid_arg "apool: max_size < init_size";
22+
let items = ref Nil in
23+
for _i = 0 to init_size - 1 do
24+
let@ _sp = Trace.with_span ~__FILE__ ~__LINE__ "apool.create.mk-item" in
25+
let item = mk_item () in
26+
items := Cons (size_ !items + 1, item, !items)
27+
done;
28+
{ mk_item; clear; max_size; items = A.make !items }
1629

1730
let rec acquire_ self =
1831
match A.get self.items with
19-
| Nil -> self.mk_item ()
32+
| Nil ->
33+
let@ _sp = Trace.with_span ~__FILE__ ~__LINE__ "apool.acquire.mk-item" in
34+
self.mk_item ()
2035
| Cons (_, x, tl) as l ->
2136
if A.compare_and_set self.items l tl then
2237
x
2338
else
2439
acquire_ self
2540

26-
let[@inline] size_ = function
27-
| Cons (sz, _, _) -> sz
28-
| Nil -> 0
29-
3041
let release_ self x : unit =
3142
self.clear x;
3243
while

src/core/apool.mli

+7-1
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,17 @@ type 'a t
99
(** Pool of values of type ['a] *)
1010

1111
val create :
12-
?clear:('a -> unit) -> mk_item:(unit -> 'a) -> ?max_size:int -> unit -> 'a t
12+
?clear:('a -> unit) ->
13+
mk_item:(unit -> 'a) ->
14+
?init_size:int ->
15+
?max_size:int ->
16+
unit ->
17+
'a t
1318
(** Create a new pool.
1419
@param mk_item produce a new item in case the pool is empty
1520
@param max_size maximum number of item in the pool before we start
1621
dropping resources on the floor. This controls resource consumption.
22+
@param init_size initial number of items to create (default 0). This must be <= max_size.
1723
@param clear a function called on items before recycling them.
1824
*)
1925

0 commit comments

Comments
 (0)