Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created August 19, 2015 09:13
Show Gist options
  • Save mitsuji/e7ca385a91f5ef9a278e to your computer and use it in GitHub Desktop.
Save mitsuji/e7ca385a91f5ef9a278e to your computer and use it in GitHub Desktop.
Producer-Consumer by STM
import Control.Concurrent(forkIO,threadDelay)
import qualified Control.Concurrent.STM.TChan as TChan
import qualified Control.Monad.STM as STM
main = do
rp <- TChan.newTChanIO
pc <- TChan.newTChanIO
forkIO $ produce pc
forkIO $ produce pc
forkIO $ produce pc
forkIO $ consume 0 rp pc
forkIO $ consume 1 rp pc
forkIO $ consume 2 rp pc
forkIO $ consume 3 rp pc
forkIO $ consume 4 rp pc
forkIO $ consume 5 rp pc
forkIO $ consume 6 rp pc
forkIO $ consume 7 rp pc
forkIO $ consume 8 rp pc
forkIO $ consume 9 rp pc
report rp
produce :: TChan.TChan Int -> IO()
produce c = loop 0
where
loop n = do
STM.atomically $ TChan.writeTChan c n
threadDelay 10
loop $ n+1
consume :: Int -> TChan.TChan String -> TChan.TChan Int -> IO()
consume id rp pc = loop
where
loop = do
n <- STM.atomically $ TChan.readTChan pc
STM.atomically $ TChan.writeTChan rp $ "consume:" ++ (show id) ++ ":" ++ (show n)
threadDelay 100
loop
report :: TChan.TChan String -> IO()
report c = loop
where
loop = do
msg <- STM.atomically $ TChan.readTChan c
putStrLn msg
loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment