Skip to content

Instantly share code, notes, and snippets.

@eborden
Created September 4, 2018 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eborden/57dde013c9488e60bf37f234d415bc47 to your computer and use it in GitHub Desktop.
Save eborden/57dde013c9488e60bf37f234d415bc47 to your computer and use it in GitHub Desktop.
$ ./take-throw-test.hs
with
m
...
with
m
with
m
with
m
with
m
with
take-throw-test.hs: user error (take and throw)
take-throw-test.hs: thread blocked indefinitely in an MVar operation
#!/usr/bin/env stack
-- stack --install-ghc runghc --package exceptions
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (newMVar, withMVar, takeMVar)
import Control.Exception (throwIO)
import Control.Monad (forever)
import System.IO (BufferMode(LineBuffering), hSetBuffering, stdout)
main = do
hSetBuffering stdout LineBuffering
m <- newMVar "m"
forkIO $ do
threadDelay 10000
takeMVar m
throwIO $ userError "take and throw"
forever $ do
putStrLn "with"
withMVar m putStrLn
@eborden
Copy link
Author

eborden commented Sep 4, 2018

I also tested this with a "Russian Doll" MVar and GHC still catches it

main = do
  hSetBuffering stdout LineBuffering
  n <- newMVar =<< newMVar "m"
  forkIO $ do
    threadDelay 10000

    m <- takeMVar n
    takeMVar m
    putMVar n m

    throwIO $ userError "take and throw"

  forever $ do
    putStrLn "with"
    withMVar n (`withMVar` putStrLn)

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