Skip to content
try4.hs 1.07 KiB
Newer Older
Yuanle Song's avatar
Yuanle Song committed
-- 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
Yuanle Song's avatar
Yuanle Song committed
import Control.Monad
Yuanle Song's avatar
Yuanle Song committed
import Control.Concurrent
import Control.Concurrent.STM
import Text.Printf
import System.Random

fuzz :: IO ()
fuzz = do
  seconds <- getStdRandom random :: IO Double
Yuanle Song's avatar
Yuanle Song committed
  threadDelay $ round (realToFrac (1000 * seconds))

incrementAndPrint :: TVar Integer -> IO ()
incrementAndPrint counter = do
  fuzz
  newCount <- atomically $ do
Yuanle Song's avatar
Yuanle Song committed
    modifyTVar' counter (+ 1)
Yuanle Song's avatar
Yuanle Song committed
    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"