Created
February 3, 2012 14:25
-
-
Save krdlab/1730401 to your computer and use it in GitHub Desktop.
practice: STM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Concurrent | |
import Control.Concurrent.STM | |
import System.Random | |
countUp :: Int -> IO () | |
countUp num = do | |
counter <- atomically $ newTVar 0 | |
sequence_ $ replicate num $ forkIO $ worker counter | |
putStrLn "start..." | |
printWorkerOutput counter | |
worker :: TVar Int -> IO () | |
worker counter = do | |
randomDelay 5 | |
atomically $ readTVar counter >>= return . (+1) >>= writeTVar counter | |
randomDelay :: Int -> IO () | |
randomDelay max = (getStdRandom $ randomR (1, max)) >>= sleep | |
sleep :: Int -> IO () | |
sleep sec = threadDelay $ sec * 1000000 | |
-- 1 秒間隔で表示を続ける | |
printWorkerOutput :: TVar Int -> IO () | |
printWorkerOutput counter = do | |
sleep 1 | |
(atomically $ readTVar counter) >>= putStrLn . show | |
printWorkerOutput counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment