Created
November 18, 2013 11:19
-
-
Save joastbg/7526232 to your computer and use it in GitHub Desktop.
Haskell - STM example using two threads and a TChan to communicate between the threads
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
module Main (main) where | |
import Data.Maybe | |
import Control.Applicative | |
import Control.Monad | |
import Control.Concurrent | |
import Control.Concurrent.STM.TChan | |
import GHC.Conc | |
import System.Random | |
readQ = atomically . readTChan | |
writeQ ch v = atomically $ writeTChan ch v | |
main :: IO () | |
main = do | |
queue <- atomically $ newTChan | |
readerThread queue | |
loop queue 0 | |
where loop queue v = (getStdRandom $ randomR (100000,10000000)) >>= threadDelay >> writeQ queue v >> loop queue (v+1) | |
readerThread :: TChan Integer -> IO ThreadId | |
readerThread queue = forkIO loop | |
where loop = readQ queue >>= putStrLn . (\s -> "Received: " ++ s) . show >> loop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment