Last active
August 14, 2025 18:25
-
-
Save joelmccracken/3e58633af2ec622aa0c850895a7a6ed3 to your computer and use it in GitHub Desktop.
ping-pong example
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
-- uses stm, async | |
import Control.Concurrent.STM.TChan (newTChan, readTChan, writeTChan) | |
import Control.Concurrent.STM (atomically) | |
import Control.Concurrent.Async (async, wait) | |
import Control.Monad (forever, void) | |
import Prelude | |
main :: IO () | |
main = do | |
pingerC <- atomically $ newTChan | |
pongerC <- atomically $ newTChan | |
pingPongC <- atomically $ newTChan | |
pinger <- async $ forever $ do | |
void $ atomically $ do | |
void $ readTChan pingerC | |
writeTChan pingPongC "ping!" | |
writeTChan pongerC () | |
ponger <- async $ forever $ do | |
void $ atomically $ do | |
readTChan pongerC | |
writeTChan pingPongC "pong?" | |
writeTChan pingerC () | |
pingponger <- async $ forever $ do | |
msg <- atomically $ readTChan pingPongC | |
putStrLn $ "read from channel: " <> msg | |
atomically $ writeTChan pingerC () | |
void $ wait pinger | |
void $ wait ponger | |
void $ wait pingponger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
results: