Skip to content

Instantly share code, notes, and snippets.

@qnikst
Created May 21, 2012 12:57
Show Gist options
  • Save qnikst/2762191 to your computer and use it in GitHub Desktop.
Save qnikst/2762191 to your computer and use it in GitHub Desktop.
stm timeout
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