[Haskell-cafe] Mixing IO and STM

Quan Ta quancta at gmail.com
Thu Dec 29 14:47:55 EST 2005


Hello folks,

Newbie question: how can I do something like the following? mixing IO and
STM.

module Test where

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

test_Cubby =
  do
    tv <- newTVar 0
    forkIO (producer tv) >> (consumer tv)
  where
    producer tv = do r <- randomRIO (1,10)
                     atomically (do { v <- readTVar tv
                                    ; writeTVar tv (v+r)
                                    })
                     print ("insert " ++ show r)
                     producer tv
                     return ()
    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)
                     consumer tv
                     return ()


Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org//pipermail/haskell-cafe/attachments/20051229/06b3e2f7/attachment.htm


More information about the Haskell-Cafe mailing list