Time out

Simon Marlow simonmar@microsoft.com
Tue, 10 Sep 2002 11:58:13 +0100


> What is the recommended way of implementing the function:
>=20
>   timeOut :: Int -> IO a -> IO (Maybe a)
>=20
> which takes a maximum number of seconds (say), an IO action,
> and tries to run the IO action in the specified time. If it
> succeeds, it returns just the answer, otherwise it returns
> Nothing.
>=20
> Do I have to start two threads, one that waits and then
> throws an exception, the other that evaluates the IO action?
>=20
> Or is there a better way? (I thought of asynchronous
> exceptions...)

With asyncrhonous exceptions as they are implemented currently, you only
need one extra thread.  If we ever get around to changing the semantics
as per the async exceptions paper, then you'll probably need two
threads.

Anyway, the way to do it is:

  - fork off a thread which sleeps for the specified period
    and then raises an exception in the parent thread
 =20
  - in the parent thread, run the IO action.  If it completes,
    kill the child thread.  You are guaranteed by the semantics
    of killThread that both threads can't kill each other
    simultaneously.

Cheers,
	Simon