Last active
November 22, 2022 09:37
-
-
Save mheiber/3cd323b3a191b04b2f05d2656bf57705 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* run like this: ocamlc unix.cma par.ml && ./a.out *) | |
open StdLabels | |
let par_iter (items: 'i list) ~(f: 'i -> unit): unit = | |
let orig_pid = Unix.getpid () in | |
let rec loop pids = function | |
| [] -> pids | |
| h :: t -> | |
match Unix.fork () with | |
| 0 -> f h; pids | |
| pid -> loop (pid :: pids) t | |
in | |
let pids = loop [] items in | |
if Unix.getpid () = orig_pid then begin | |
List.iter pids ~f:(fun pid -> ignore @@ Unix.waitpid [] pid) | |
end else | |
exit 0 | |
let () = (* usage **) | |
let slow_print_int work = | |
Random.self_init (); | |
let wait_seconds = Random.int 3 in | |
Unix.sleep @@ 1 + wait_seconds; | |
Format.printf "work %d started\n" work; | |
let rec loop n = | |
if n < 9999999 then loop @@ n + 1 | |
in loop 0; | |
Format.print_flush (); | |
Format.printf "work %d finished in %d seconds\n" work wait_seconds; | |
Format.print_flush () | |
in | |
par_iter [1; 2; 3; 4; 5;] ~f:slow_print_int; | |
par_iter ["hello"; "world"] ~f:print_endline; | |
(* example output: | |
work 2 started | |
work 2 finished in 0 seconds | |
work 1 started | |
work 1 finished in 1 seconds | |
work 3 started | |
work 3 finished in 2 seconds | |
work 4 started | |
work 4 finished in 2 seconds | |
hello | |
world | |
*) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment