[Haskell-cafe] Mixing IO and STM

Quan Ta quancta at gmail.com
Thu Dec 29 15:32:52 EST 2005


On 12/29/05, Brian Sniffen <brian.sniffen at gmail.com> wrote:
>
> > test_Cubby =
> >   do
> >     tv <- newTVar 0
>
> You've almost got it!  But "newTVar 0" has type STM Tvar, and you're
> trying to use it in the IO monad.  So just say "tv <- atomically
> (newTVar 0)" and you're set.  Do notice that you'll see output like
> this:
>
> co"nisnusmeer t6 "6
> "
> "c"oinnssuemret  61""
>
> ""cionnsseurmte  95""
>
> ""icnosnesrutm e2 "9
>
> since the two threads are interleaved.
>
> --
> Brian T. Sniffen
> bts at alum.mit.edu    or    brian.sniffen at gmail.com
> http://www.evenmere.org/~bts
>


Thank you all for your help and comments ...

module Main where

import System.Random
import Control.Concurrent
import Control.Concurrent.STM


forever act = act >> forever act

 test_Cubby =
  do
    tv <- atomically (newTVar 0)
    forkIO (forever $ producer tv) >> (forever $ consumer tv)
  where
    producer tv = do r <- randomRIO (1,10)
                     atomically (do { v <- readTVar tv
                                    ; writeTVar tv (v+r)
                                    })
                     print ("insert " ++ show r)
                     threadDelay r
    consumer tv = do r <- randomRIO (1,10)
                     atomically (do { v <- readTVar tv
                                    ; if (v < r) then retry
                                      else writeTVar tv (v-r)
                                    })
                     print ("consume " ++ show r)
                     threadDelay r

I also slow it down a bit to get readable output ... thanks again.
- Quan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org//pipermail/haskell-cafe/attachments/20051229/928e27d5/attachment-0001.htm


More information about the Haskell-Cafe mailing list