Created
May 21, 2012 12:57
-
-
Save qnikst/2762191 to your computer and use it in GitHub Desktop.
stm timeout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Monad | |
import Control.Concurrent | |
import Control.Concurrent.STM | |
import Control.Concurrent.STM.TVar | |
import Control.Concurrent.STM.TMVar | |
import Data.Maybe | |
stmTimeout :: Int -> IO a -> IO (Maybe a) | |
stmTimeout timeout action = do | |
tOut <- registerDelay timeout | |
result <- newEmptyTMVarIO | |
workerId <- forkIO $ action >>= atomically . (putTMVar result) | |
o <- atomically $ do | |
end <- readTVar tOut | |
if end then return Nothing | |
else tryTakeTMVar result >>= maybe retry (return . Just) | |
when (not $! isJust o) $ killThread workerId `catch` (const $ return ()) | |
return o |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment