Last active
March 17, 2022 11:03
-
-
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/
This file contains hidden or 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 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