Difference between revisions of "Simple STM example"

From HaskellWiki
Jump to navigation Jump to search
m (category)
m
 
(4 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
<haskell>
 
<haskell>
  +
{-# OPTIONS_GHC -rtsopts -with-rtsopts=-N4 -threaded -Wall #-}
 
module Main where
 
module Main where
 
import Control.Monad
 
import Control.Monad
Line 5: Line 6:
 
import Control.Concurrent.STM
 
import Control.Concurrent.STM
   
  +
main :: IO ()
main = do shared <- atomically $ newTVar 0
+
main = do shared <- newTVarIO (0 :: Int)
 
before <- atomRead shared
 
before <- atomRead shared
putStrLn $ "Before: " ++ show before
+
putStrLn ("Before: " ++ show before)
forkIO $ 25 `timesDo` (dispVar shared >> milliSleep 20)
+
repeatIO 25 (dispVar shared >> threadDelay 20_000)
forkIO $ 10 `timesDo` (appV ((+) 2) shared >> milliSleep 50)
+
repeatIO 10 (appV (+ 2) shared >> threadDelay 50_000)
forkIO $ 20 `timesDo` (appV pred shared >> milliSleep 25)
+
repeatIO 20 (appV pred shared >> threadDelay 25_000)
milliSleep 800
+
threadDelay 800_000
 
after <- atomRead shared
 
after <- atomRead shared
putStrLn $ "After: " ++ show after
+
putStrLn ("After: " ++ show after)
  +
where
where timesDo = replicateM_
 
milliSleep = threadDelay . (*) 1000
+
repeatIO n = void . forkIO . replicateM_ n
  +
atomRead = readTVarIO
 
 
dispVar x = atomRead x >>= print
atomRead = atomically . readTVar
 
 
appV fn x = atomically (modifyTVar x fn)
dispVar x = atomRead x >>= print
 
appV fn x = atomically $ readTVar x >>= writeTVar x . fn
 
 
</haskell>
 
</haskell>
 
[[Category:Monad]]
 
[[Category:Monad]]
  +
[[Category:Code]]

Latest revision as of 09:01, 9 September 2024

{-# OPTIONS_GHC -rtsopts -with-rtsopts=-N4 -threaded -Wall #-}
module Main where
import Control.Monad
import Control.Concurrent
import Control.Concurrent.STM

main :: IO ()
main = do shared <- newTVarIO (0 :: Int)
          before <- atomRead shared
          putStrLn ("Before: " ++ show before)
          repeatIO 25 (dispVar shared >> threadDelay 20_000)
          repeatIO 10 (appV (+ 2) shared >> threadDelay 50_000)
          repeatIO 20 (appV pred shared >> threadDelay 25_000)
          threadDelay 800_000
          after <- atomRead shared
          putStrLn ("After: " ++ show after)
  where
    repeatIO n = void . forkIO . replicateM_ n
    atomRead = readTVarIO
    dispVar x = atomRead x >>= print
    appV fn x = atomically (modifyTVar x fn)