Skip to content

Instantly share code, notes, and snippets.

@vdorr
Last active April 2, 2025 11:49
Show Gist options
  • Save vdorr/cfc97e298d34d0a586012cdea0972e37 to your computer and use it in GitHub Desktop.
Save vdorr/cfc97e298d34d0a586012cdea0972e37 to your computer and use it in GitHub Desktop.
Timeout in Haskell STM monad
-- important: compile with -threaded
import Control.Concurrent.STM
import Control.Applicative
-- |Wait for STM action specified amount of time and return value of action or default value if action times out
stmTimeout' :: Int -> a -> STM a -> IO a
stmTimeout' microseconds defVal f
= registerDelay microseconds
>>= \timeouted -> atomically $
f
<|> defVal <$ (readTVar timeouted >>= check)
-- |Version of stmTimeout' that returns Maybe instead of default value
stmTimeout :: Int -> STM a -> IO (Maybe a)
stmTimeout microseconds f = stmTimeout' microseconds Nothing (Just <$> f)
@AleXoundOS
Copy link

AleXoundOS commented Jun 13, 2022

Why does this require -threaded and is it still the case with modern GHC?

@vdorr
Copy link
Author

vdorr commented Jun 15, 2022

gist was written for 8.something, but i believe -threaded is still required, per hacakge https://hackage.haskell.org/package/base-4.16.1.0/docs/Control-Concurrent.html#g:5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment