Skip to content

Instantly share code, notes, and snippets.

@joastbg
Created November 18, 2013 11:19
Show Gist options
  • Save joastbg/7526232 to your computer and use it in GitHub Desktop.
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
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