|
Re: Implementing computations with timeout: msg#00091lang.haskell.cafe
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> |
|---|---|---|
| Previous by Date: | RE: Unicode: Hugs vs GHC (again) was: Re: Some random newbie questions: 00091, Simon Marlow |
|---|---|
| Next by Date: | Re: Implementing computations with timeout: 00091, Einar Karttunen |
| Previous by Thread: | Implementing computations with timeouti: 00091, Einar Karttunen |
| Next by Thread: | Re: Implementing computations with timeout: 00091, Einar Karttunen |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |