Browse thread
[ANN] coThreads 0.10
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: | 2007-09-20 (09:08) |
From: | Zheng Li <li@p...> |
Subject: | Re: Can coThreads be used for message passing architecture? |
Hi, Nice try! Erik de Castro Lopo <mle+ocaml@mega-nerd.com> writes: > All my examples so far are trivial, like the following which creates a > Cothread and then polls for an event sent by the child. > > ------------------------------------------------------------------- > (* > ** Needs Cothreads installed : > ** http://cothreads.sourceforge.net/ > ** > ** Run with : > ** ocaml -I +process unix.cma cothreads.cma poll_event.ml > ** > ** Native compile with : > ** ocamlopt -I +process unix.cmxa cothreads.cmxa poll_event.ml -o poll_event > *) One comment: you don't have to hard-wired "Cothread.xxx" into source, since all the functions you're using are compatible between Thread and Cothread modules, and moreover, coThreads does provide a compatible version of threads.cm(x)a and Thread module being able to work with process. So by "open Cothread" or "open Thread" or "module Thread=Cothread", you'll be given more flexibility to change easily back and forth between coThreads and standard Threads (image sometime later you need to deploy the same code to a standard-OCaml-only environment ...) > let child_thread chan = > (* Print thread id (actually process id) and flush stdout. *) > Printf.printf "child_thread : %d\n%!" (Cothread.id (Cothread.self ())) ; > (* Hang about for a bit. *) > Cothread.delay 2.5 ; > (* Send an event. *) > Event.sync (Event.send chan "Event from child.") ; > (* Hang about a bit more. *) > Cothread.delay 1.5 ; > Cothread.exit () > > let () = > (* Create an event channel for sending stuff between main and child. *) > let chan = Event.new_channel () in > (* Create the child thread and pass it the channel. *) > let t1 = Cothread.create child_thread chan in > (* Set the exit condition to false. *) > let fini = ref false in > while not !fini do > (* Now we can poll on the incoming event. *) > match (Event.poll (Event.receive chan)) with > | None -> Printf.printf "Nothing.\n%!" ; Cothread.delay 0.3 > | Some s -> fini := true ; print_endline s > done ; > (* Wait for child thread to exit. *) > Printf.printf "Waiting for child thread.\n%!" ; > Cothread.join t1 ; > print_endline "Done." > > ------------------------------------------------------------------- > > I intend to blog about this over the weekend. I'll post a URL when > its done. -- Zheng Li http://www.pps.jussieu.fr/~li