[Haskell-cafe] Implementing computations with timeout
tomasz.zielonka at gmail.com
Fri Jan 7 08:57:19 EST 2005
On Fri, Jan 07, 2005 at 03:31:10PM +0200, Einar Karttunen wrote:
> 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)
withTimeout :: Int -> STM a -> IO (Maybe a)
withTimeout time fun = do
mv <- atomically newEmptyTMVar
tid <- forkIO $ do
atomically (putTMVar mv ())
x <- atomically (fmap Just fun `orElse` (takeTMVar mv >> return Nothing))
PS. STM is cool! :)
More information about the Haskell-Cafe