Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Lwt_stream.iter_n #312

Merged
merged 1 commit into from
Feb 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/core/lwt_stream.ml
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,33 @@ let rec iter_p_rec node f s =

let iter_p f s = iter_p_rec s.node f s

let iter_n ?(max_threads = 1) f stream =
begin
if max_threads <= 0 then
let message =
Printf.sprintf "Lwt_stream.iter_n: max_threads must be > 0, %d given"
max_threads
in
invalid_arg message
end;
let rec loop running available =
begin
if available > 0 then (
Lwt.return (running, available)
)
else (
Lwt.nchoose_split running >>= fun (complete, running) ->
Lwt.return (running, available + List.length complete)
)
end >>= fun (running, available) ->
get stream >>= function
| None ->
Lwt.join running
| Some elt ->
loop (f elt :: running) (pred available)
in
loop [] max_threads

let rec find_rec node f s =
if node == !(s.last) then
feed s >>= fun () -> find_rec node f s
Expand Down
7 changes: 7 additions & 0 deletions src/core/lwt_stream.mli
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,13 @@ val iter_p : ('a -> unit Lwt.t) -> 'a t -> unit Lwt.t
val iter_s : ('a -> unit Lwt.t) -> 'a t -> unit Lwt.t
(** [iter f s] iterates over all elements of the stream. *)

val iter_n : ?max_threads:int -> ('a -> unit Lwt.t) -> 'a t -> unit Lwt.t
(** [iter_n ?max_threads f s] iterates over all elements of the stream [s].
Iteration is performed concurrently with up to [max_threads] concurrent
instances of [f].

@param max_threads defaults to [1]. *)

val find : ('a -> bool) -> 'a t -> 'a option Lwt.t
val find_s : ('a -> bool Lwt.t) -> 'a t -> 'a option Lwt.t
(** [find f s] find an element in a stream. *)
Expand Down