
On 12/29/05, Brian Sniffen
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@alum.mit.edu or brian.sniffen@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