Created
February 3, 2012 14:41
-
-
Save krdlab/1730476 to your computer and use it in GitHub Desktop.
practice: Channel
This file contains hidden or 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.Monad (forM_) | |
import Control.Concurrent | |
import Control.Concurrent.Chan | |
import Control.Concurrent.STM | |
import System.Random | |
postString :: Int -> IO () | |
postString num = do | |
ch <- atomically newTChan | |
forM_ [1..num] $ forkIO . worker ch | |
putStrLn "start..." | |
loopMain ch | |
worker :: TChan String -> Int -> IO () | |
worker chan idx = do | |
randomDelay 5 | |
atomically $ writeTChan chan $ "thread-" ++ show idx -- とりあえず文字列 | |
-- 取り切ったらブロックしちゃうけど... | |
loopMain :: TChan String -> IO () | |
loopMain chan = (atomically $ readTChan chan) >>= putStrLn >> loopMain chan | |
randomDelay :: Int -> IO () | |
randomDelay max = (getStdRandom $ randomR (1, max)) >>= threadDelay . (*1000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment