Version française
Home     About     Download     Resources     Contact us    
Browse thread
[ANN] coThreads 0.10
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Erik de Castro Lopo <mle+ocaml@m...>
Subject: Re: [Caml-list] Can coThreads be used for message passing architecture?
Jon Harrop wrote:

> Carry on... :-)
> 
> Any examples?

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
*)

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.

Erik
-- 
-----------------------------------------------------------------
Erik de Castro Lopo
-----------------------------------------------------------------
"I believe C++ instills fear in programmers, fear that the
interaction of some details causes unpredictable results. Its
unmanageable complexity has spawned more fear-preventing tools
than any other language, but the solution _should_ have been
to create and use a language that does not overload the
whole goddamn human brain with irrelevant details."
-- Erik Naggum