[Shootout-list] Process for OCaml

William Douglas Neumann wdnx@unm.edu
Fri, 17 Dec 2004 09:57:45 -0700 (MST)


Below is the OCaml submission for the process benchmark.  As with the 
message benchmark, I don't really like it, but the "elegant" version using 
the Event module is much slower, and I'm not really sure why (not that 
this version is exactly screaming, but it's my first foray into concurrent 
programming in OCaml [and my first in any language in a long, long time], 
so it's possible I'm doing something really stupid...). Meh... at least it 
works.



(* process.ml :
   Requires the threads and unix libraries, so compile with something like
     ocamlopt  -I +threads unix.cmxa threads.cmxa process.ml -o process
*)

type thCtx =
   { mutable message : int;
     mutable busy : bool;
     lock : Mutex.t;
     cond : Condition.t };;

let makeThread () =
   { message = ~-1; busy = false; lock = Mutex.create (); cond = 
Condition.create () };;

let put th msg =
   Mutex.lock th.lock;
   while th.busy do Condition.wait th.cond th.lock done;
   th.busy <- true; th.message <- msg;
   Condition.signal th.cond;
   while th.message <> ~-1 do Condition.wait th.cond th.lock done;
   th.busy <- false;
   Condition.signal th.cond;
   Mutex.unlock th.lock;;

let take th =
   while th.message = ~-1 do Condition.wait th.cond th.lock done;
   let m = th.message in
     th.message <- ~-1;
     Condition.signal th.cond;
     (succ m);;

let link th next =
   while true do put next (take th) done;;

let rec endLink th =
   print_int (take th); print_newline ();;

let rec loop th n =
   if n > 0 then (put th 0; loop th (pred n));;

let _ =
   let n = int_of_string Sys.argv.(1) in
   let thEnd = makeThread () in
   let chainEnd = Thread.create endLink thEnd in
   let rec mkLinks n next =
     if n < 1 then next
     else
       let cur = makeThread () in
       (ignore (Thread.create (link cur) next); mkLinks (pred n) cur) in
   let firstLink = mkLinks (pred n) thEnd in
   put firstLink 0;
   Thread.join chainEnd;;

William D. Neumann
<wdnx@unm.edu>

FWO to the Nth degree!!!
---
Dear Lord, please make me the kind of person
my dog thinks I am.