Last active
April 2, 2025 11:49
-
-
Save vdorr/cfc97e298d34d0a586012cdea0972e37 to your computer and use it in GitHub Desktop.
Timeout in Haskell STM monad
This file contains hidden or 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
-- 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) |
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
Why does this require
-threaded
and is it still the case with modern GHC?