[Shootout-list] process creation & message passing chain

skaller skaller@users.sourceforge.net
06 Nov 2004 21:06:59 +1100


OK, here's an Ocaml version (it's out by 1 somewhere):

[skaller@pelican] ~>ocamlc -o evt -thread unix.cma threads.cma evt.ml
[skaller@pelican] ~>time ./evt 200 200
Thread count 200
Message count 200
40200
 
real    0m2.679s
user    0m2.130s
sys     0m0.440s
-----------------------------------------------
open Thread
open Event

let thread_count = int_of_string Sys.argv.(1)
let message_count = int_of_string Sys.argv.(2)
let si i = string_of_int i 
;;
print_endline  ("Thread count " ^ si thread_count);;
print_endline  ("Message count " ^ si message_count);;

let finalthr inchan = 
  let total = ref 0 in
  try
    while true do
      let i = sync (receive inchan) in
      if i = -1 then raise Not_found
      else total := !total + i
    done;
  with Not_found -> print_endline (si !total)

let rec mkthr (i,inchan) =
  let outchan = new_channel () in
  let next =
    if i > 0 then 
      Thread.create mkthr ((i-1),outchan)
    else
      Thread.create finalthr (outchan)
  in
  try 
    while true do
      let k = sync (receive inchan) in
      if k = -1 then raise Not_found;
      sync (send outchan (k+1))
    done
  with Not_found ->
    sync (send outchan (-1));
    Thread.join next
    

let main() = 
  let outchan = new_channel () in
  let thr = Thread.create mkthr (thread_count,outchan) in
  for i = 1 to message_count do
    sync (send outchan 0)
  done;
  sync (send outchan (-1));
  Thread.join thr
;;
main()
;;

-- 
John Skaller, mailto:skaller@users.sf.net
voice: 061-2-9660-0850, 
snail: PO BOX 401 Glebe NSW 2037 Australia
Checkout the Felix programming language http://felix.sf.net