[Haskell-cafe] Implementing computations with timeout

Einar Karttunen ekarttun at cs.helsinki.fi
Fri Jan 7 08:31:10 EST 2005


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)
withTimeout time fun =
  do mv <- newEmptyMVar
     tid <- forkIO (fun  >>= tryPutMVar mv . Just >> return ())
     forkIO (threadDelay time >>  killThread tid >> tryPutMVar mv Nothing >> return ())
     takeMVar mv 

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

- Einar Karttunen

More information about the Haskell-Cafe mailing list