[Haskell-cafe] Mixing IO and STM
Lemmih
lemmih at gmail.com
Thu Dec 29 14:54:16 EST 2005
On 12/29/05, Quan Ta <quancta at gmail.com> wrote:
> 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
Change this:
> tv <- newTVar 0
To this:
> tv <- atomically (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 ()
--
Friendly,
Lemmih
More information about the Haskell-Cafe
mailing list