Skip to content

Instantly share code, notes, and snippets.

@Decoherence
Last active August 29, 2015 14:11
Show Gist options
  • Save Decoherence/689901bd2642479d6df5 to your computer and use it in GitHub Desktop.
Save Decoherence/689901bd2642479d6df5 to your computer and use it in GitHub Desktop.
Haskell: Software Transactional Memory (STM) -- read & write integers concurrently to a channel
import Control.Monad.STM
import Control.Concurrent
import Control.Concurrent.STM.TChan
oneSecond = 1000000 -- microseconds
-- | This thread writes values to a channel.
writerThread :: TChan Int -> IO ()
writerThread chan = do
-- Wait two seconds, then write 1 to channel
threadDelay $ 2 * oneSecond
atomically $ writeTChan chan 1
-- Wait another sec, then write 2 to channel
threadDelay oneSecond
atomically $ writeTChan chan 2
-- Wait a sec, then write 3, then wait a sec
threadDelay oneSecond
atomically $ writeTChan chan 3
threadDelay oneSecond
-- | And this thread listens for values on a channel, and prints each value when received.
readerThread :: TChan Int -> IO ()
readerThread chan = do
-- Create a channel and start listening
newInt <- atomically $ readTChan chan
putStrLn $ "read new value: " ++ show newInt
readerThread chan
-- | Main entry point
main = do
chan <- atomically $ newTChan -- create a new channel
forkIO $ readerThread chan -- spark thread the reader
forkIO $ writerThread chan -- spark thread for writer
threadDelay $ 5 * oneSecond -- keep main thread alive until writerThread is finished
{-
OUTPUT:
λ main
read new value: 1
read new value: 2
read new value: 3
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment