Is it true that an exception is always terminates the thread?

Edward Z. Yang ezyang at MIT.EDU
Mon Jan 23 22:26:38 CET 2012


Excerpts from Heka Treep's message of Mon Jan 23 16:20:51 -0500 2012:
> actor :: TChan String -> IO ()
> actor mbox = forever $ do
>   putStrLn "call to actor..."
>   msg <- atomically $ do
>     isEmpty <- isEmptyTChan mbox
>     if isEmpty then return Nothing else readTChan mbox >>= return . Just
>   when (isJust msg) $ putStrLn $ fromJust msg

There are several things wrong with this:

    - You're only synchronizing over one variable: use an Chan, not a TChan
      (if you make that change, btw, it will automatically start working.)

    - You don't want the transaction to succeed in all cases; you only want
      the transaction to succeed if you manage to get something from the
      TChan.  What you've done is convert the interface from blocking
      to non-blocking, but in a busy-loop.

    - You don't even need to run isEmptyTChan. Just do a readTChan. It will
      block if there is nothing in the chan (technically, it will ask the
      STM transaction to retry, but STM is clever enough not to try running
      again unless any of the touched STM variables changes.)

Edward



More information about the Glasgow-haskell-users mailing list