[Haskell-cafe] Implementing computations with timeout

Sebastian Sylvan sebastian.sylvan at gmail.com
Fri Jan 7 14:56:42 EST 2005


On Fri, 07 Jan 2005 15:31:10 +0200, Einar Karttunen
<ekarttun at cs.helsinki.fi> wrote:
> Hello
> 
> What is the best way of doing an computation with a timeout?

I like the approach taken in  "Tackling the ackward squad":

First a funcion which will "race" two IO computations against each
other, returning the "winning" result.
This is accomplished by simply spawning a thread for each computation
which does nothing but evalute the IO computation and putting the
result in an MVar.
Then the MVar is read (this will lock until there is something in the
MVar to read), when finally there is something to read it will
obviously contain the result of the IO computation that completed
first. Then both of the spawned threads are killed (one of them is
already dead at this point) via throwTo.

parIO :: IO a -> IO a -> IO a
parIO a1 a2
 = do m <- newEmptyMVar ;
        c1 <- forkIO (child m a1) ;
        c2 <- forkIO (child m a2) ;
        r <- takeMVar m ;
        throwTo c1 Kill ;
        throwTo c2 Kill ;
        return r
 where child m a = do r <- a
                                putMVar m r 

Next we simply race the IO computation to be "timed out" against a
thread which delays and then returns Nothing.

timeout :: Int -> IO a -> IO (Maybe a)
timeout n a = parIO a1 a2
where a1 = do r <-a
                      return (Just r)
          a2 = do threadDelay n
                      return Nothing


/S

-- 
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862


More information about the Haskell-Cafe mailing list