Browse thread
[Caml-list] Native Threads
[
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: | -- (:) |
| From: | Alessandro Baretta <alex@b...> |
| Subject: | Re: [Caml-list] Native Threads |
nadji@noos.fr 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
end
module Finite_time_thread (M:Exec_with_timeout) = struct
let start arg =
let kill_request () = Thread.delay M.timeout; M.run :=
false in
let t1 = Thread.create M.f arg in
let t2 = Thread.create kill_request () in
Thread.join t1
end
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 Foo.run to verify that it still has time. When,
upon testing Foo.run, Foo.f discovers that it has consumed
all the allotted time, it must return.
Alex
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners