Difference between revisions of "Simple STM example"
Jump to navigation
Jump to search
m |
|||
(3 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 <- |
+ | main = do shared <- newTVarIO (0 :: Int) |
before <- atomRead shared |
before <- atomRead shared |
||
− | putStrLn |
+ | 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 |
after <- atomRead shared |
||
− | putStrLn |
+ | putStrLn ("After: " ++ show after) |
+ | where |
||
− | where timesDo = replicateM_ |
||
− | + | repeatIO n = void . forkIO . replicateM_ n |
|
+ | atomRead = readTVarIO |
||
− | |||
⚫ | |||
− | atomRead = atomically . readTVar |
||
⚫ | |||
⚫ | |||
⚫ | |||
</haskell> |
</haskell> |
||
[[Category:Monad]] |
[[Category:Monad]] |
||
[[Category:Code]] |
[[Category:Code]] |
||
− | [[Category:Example]] |
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)