Skip to content

Instantly share code, notes, and snippets.

@krdlab
Created February 3, 2012 14:41
Show Gist options
  • Save krdlab/1730476 to your computer and use it in GitHub Desktop.
Save krdlab/1730476 to your computer and use it in GitHub Desktop.
practice: Channel
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