Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Native Threads
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-10-06 (14:24)
From: Alessandro Baretta <alex@b...>
Subject: Re: [Caml-list] Native Threads wrote:
> Hi,
> Or, does someone knows how to implement a function
>  timeout: float -> (unit->unit) -> unit
> which executes the function given in argument , but
> no more than a certain amount of time, without Thread.kill ?
> TIA,
> Nadji

If you want synchronous killing you're in a mess, but if I 
can live with an asynchronous model, here's how you might go 
about with it.
module type Exec_with_timeout = sig
val run : bool ref
val f : 'a -> unit
val timeout : float

module Finite_time_thread (M:Exec_with_timeout) = struct
let start arg =
   let kill_request () = Thread.delay M.timeout; := 
false in
   let t1 = Thread.create M.f arg in
   let t2 = Thread.create kill_request () in
     Thread.join t1

let module Foo : Exec_with_timeout = struct
let run = ref true
let f () = while !run do () (*Your code here*) done
let timeout = 5.0 (* number of seconds this will run *)
end in
let Finite_foo_thread = Finite_time_thread Foo in
Finite_foo_thread.start ()

This requires that Foo.f work cooperatively by periodically 
checking to verify that it still has time. When, 
upon testing, Foo.f discovers that it has consumed 
all the allotted time, it must return.


To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: