logo       

Re: Implementing computations with timeout: msg#00091

lang.haskell.cafe

Subject: Re: Implementing computations with timeout

On Fri, Jan 07, 2005 at 03:31:10PM +0200, Einar Karttunen wrote:
> Hello
>
> What is the best way of doing an computation with a timeout?
>
> A naive implementation using two threads is easy to create - but
> what is the preferred solution?
>
> withTimeout :: forall a. Int -> IO a -> IO (Maybe a)

> btw How would I do the same with the new STM abstraction?

My guess is it would be something like this, however you may want to do it
differently to get better compositionality (withTimeout returns an IO action,
not a STM action):

import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.STM

withTimeout :: Int -> STM a -> IO (Maybe a)
withTimeout time fun = do
mv <- atomically newEmptyTMVar
tid <- forkIO $ do
threadDelay time
atomically (putTMVar mv ())
x <- atomically (fmap Just fun `orElse` (takeTMVar mv >> return Nothing))
killThread tid
return x

PS. STM is cool! :)

Best regards,
Tomasz


<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise