[Haskell-cafe] STM atomic blocks in IO functions

Rob Stewart robstewart57 at googlemail.com
Sat Jan 14 20:24:36 CET 2012


On 14 January 2012 18:05, Steffen Schuldenzucker
<sschuldenzucker at uni-bonn.de> wrote:

> I think "consistent state" here means that you can be sure no other thread
> has modified a, say, TVar, within the current 'atomically' block.

OK, well take a modified example, where I am wanting to call an IO
function within an atomically block:
---
import Control.Concurrent.STM
import Control.Monad.IO.Class (liftIO)

addThree :: TVar Int -> Int -> STM ()
addThree t = do
  i <- liftIO three -- Problem line
  ls <- readTVar t
  writeTVar t (ls + i)

three :: IO Int
three = return 3

main :: IO ()
main = do
  val <- atomically $ do
   tvar <- newTVar 0
   addThree tvar
   readTVar tvar
  putStrLn $ "Value: " ++ show val
---

Are IO functions permissible in STM atomically blocks? If so how? If
not, how would one get around a problem of having to use an IO
function to retrieve a value that is to be written to a TVar ?

--
Rob



More information about the Haskell-Cafe mailing list