[Haskell-cafe] STM atomic blocks in IO functions

Daniel Waterworth da.waterworth at gmail.com
Sat Jan 14 21:15:17 CET 2012


On 14 January 2012 19:24, Rob Stewart <robstewart57 at googlemail.com> wrote:
> 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

No that's not possible. An STM transaction may be tried several times
so allowing IO doesn't make sense. Instead you pass any values that
you need into the transaction. e.g.

line <- getLine
atomically $ do
  writeTVar v line
  ...

Daniel



More information about the Haskell-Cafe mailing list