Commit 50d6631d authored by Yuanle Song's avatar Yuanle Song
Browse files

add try4.hs on STM

parent 005e98d3
Loading
Loading
Loading
Loading
Loading
+7 −0
Original line number Diff line number Diff line
@@ -49,6 +49,13 @@ executable testQueue
                     , random
  default-language:    Haskell2010

executable try4
  main-is:             try4.hs
  ghc-options:         -threaded -rtsopts -with-rtsopts=-N
  build-depends:       base
                     , random
                     , stm
  default-language:    Haskell2010

source-repository head
  type:     git
+1 −0
Original line number Diff line number Diff line
@@ -24,3 +24,4 @@ main = do
  counter <- newMVar 0
  replicateM_ 10 (forkIO $ incrementAndPrint counter)
  putStrLn "Finishing up"
  threadDelay 1000000

try4.hs

0 → 100644
+35 −0
Original line number Diff line number Diff line
-- 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
    modifyTVar' counter (\i -> i + 1)
    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"