Version française
Home     About     Download     Resources     Contact us    
Browse thread
Timeouts in Event module
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Markus Mottl <markus.mottl@g...>
Subject: Re: [Caml-list] Timeouts in Event module
On Sun, 23 Jan 2005, Yaron Minsky wrote:
> Thanks.  That looks quite useful.    I suppose one could create a
> timed event by creating a channel and scheduling a callback to send on
> that channel.  It seems like a bit of a hack (not your library, but
> the need to use such a mechanism to simulate timeouts), but it should
> do the job.

I remember having found the following solution, which I use in my projects
now, on the list a while ago:

  let watchdog s v =
    let ch = Event.new_channel () in
    let watchdog_thread () =
      Thread.delay s;
      Event.sync (Event.send ch v) in
    ignore (Thread.create watchdog_thread ());
    Event.receive ch

  let timed_sync s v event = Event.sync (Event.choose [event; watchdog s v])

You can use it e.g. as follows:

  let thread_fun ch =
    (* ... do something long ... *)
    Event.sync (Event.send result) in
  let ch = Event.new_channel () in
  let tid = Thread.create thread_fun ch in
  timed_sync 3.14 default_value (Event.receive ch)

If "thread_fun" doesn't send + synchronize a result within 3.14 seconds
on event channel "ch", then "default_value" will be returned, the result
otherwise.

Regards,
Markus

-- 
Markus Mottl    markus.mottl@gmail.com    http://www.ocaml.info