[Haskell-cafe] Implementing computations with timeout

Tomasz Zielonka 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:
> 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,

More information about the Haskell-Cafe mailing list