Skip to content

Instantly share code, notes, and snippets.

@shangaslammi
Last active March 17, 2022 11:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shangaslammi/5955676 to your computer and use it in GitHub Desktop.
Save shangaslammi/5955676 to your computer and use it in GitHub Desktop.
Direct Haskell translations of the concurrency examples at http://blog.drewolson.org/blog/2013/07/04/clojure-core-dot-async-and-go-a-code-comparison/
module ConcurrencyExamples where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Control.Applicative
import System.Random
example1 :: IO ()
example1 = do
forM_ [0..9] $ \i -> forkIO $ do
threadDelay =<< randomRIO (0, 1000000)
print i
threadDelay 2000000
example2 :: IO ()
example2 = do
c <- newChan
forM_ [0..9] $ \i -> forkIO $ do
threadDelay =<< randomRIO (0, 1000000)
writeChan c i
replicateM_ 10 $ print =<< readChan c
example3 :: IO ()
example3 = do
c <- newTChanIO
forkIO $ do
threadDelay =<< randomRIO (0, 1000000)
atomically $ writeTChan c ()
timeout <- newEmptyTMVarIO
forkIO $ do
threadDelay 500000
atomically $ putTMVar timeout ()
join . atomically
$ putStrLn "Got a value!" <$ readTChan c
<|> putStrLn "Timeout!" <$ takeTMVar timeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment