
7 Jan
2005
7 Jan
'05
9:55 a.m.
Tomasz Zielonka
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
Isn't this buggy if fun just keeps working without throwing an exception or using retry? I meant wholly inside STM - if we use IO as the signature then using the TMVar has few advantages over using an MVar. - Einar Karttunen