diff --git a/src/fut.ml b/src/fut.ml index 5fbaaee3..846b78da 100644 --- a/src/fut.ml +++ b/src/fut.ml @@ -318,6 +318,10 @@ let for_ ~on n f : unit t = let for_array ~on arr f : unit t = for_ ~on (Array.length arr) (fun i -> f i arr.(i)) +let for_list ~on l f : unit t = + let futs = List.rev_map (fun x -> spawn ~on (fun () -> f x)) l in + wait_list futs + (* ### blocking ### *) let wait_block (self : 'a t) : 'a or_error = diff --git a/src/fut.mli b/src/fut.mli index 01390c1c..99dcecb3 100644 --- a/src/fut.mli +++ b/src/fut.mli @@ -141,6 +141,10 @@ val for_array : on:Pool.t -> 'a array -> (int -> 'a -> unit) -> unit t or fails if any of them fails. @since 0.2 *) +val for_list : on:Pool.t -> 'a list -> ('a -> unit) -> unit t +(** [for_list ~on l f] is like [for_array ~on (Array.of_list l) f]. + @since 0.2 *) + (** {2 Blocking} *) val wait_block : 'a t -> 'a or_error diff --git a/test/t_futs1.ml b/test/t_futs1.ml index 412d293a..930c8bdc 100644 --- a/test/t_futs1.ml +++ b/test/t_futs1.ml @@ -132,3 +132,14 @@ let () = let () = let x = [| Fut.return 1 |] |> Fut.join_array |> Fut.wait_block_exn in assert (x = [| 1 |]) + +let () = + let run_for n = + let l = List.init n (fun x -> x) in + let sum = Atomic.make 0 in + Fut.for_list ~on:pool l (fun x -> ignore (Atomic.fetch_and_add sum x : int)) + |> Fut.wait_block_exn; + assert (Atomic.get sum = List.fold_left ( + ) 0 l) + in + + List.iter run_for [ 1; 10; 50; 1_000 ]