Newer
Older
-- can I write this using STM? I know the print part is not pure function.
-- STM can help with variable read/write, but it can't help you with IO
-- action. since there is really no variable in haskell, it's similar to try1
-- where it is implemented using locks (MVar). STM TVar is implemented using
-- transactional memory. STM can only ensure TVar and T* access is safe in
-- atomically block, it can't do anything about printing.
import System.IO
import Control.Concurrent
import Control.Concurrent.STM
import Text.Printf
import System.Random
fuzz :: IO ()
fuzz = do
seconds <- getStdRandom random :: IO Double
threadDelay $ round (realToFrac (1000 * seconds))
incrementAndPrint :: TVar Integer -> IO ()
incrementAndPrint counter = do
fuzz
newCount <- atomically $ do
readTVar counter
fuzz
printf "The count is %d\n" newCount
fuzz
putStrLn "---------------"
main :: IO ()
main = do
putStrLn "Starting up"
counter <- newTVarIO 0
replicateM_ 10 (forkIO $ incrementAndPrint counter)
putStrLn "Finishing up"