Skip to content

Instantly share code, notes, and snippets.

@zerokarmaleft
Last active December 20, 2015 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerokarmaleft/6084002 to your computer and use it in GitHub Desktop.
Save zerokarmaleft/6084002 to your computer and use it in GitHub Desktop.
core.async example: Ping Pong
(defn player
[msg table]
(go (loop []
(let [ball (<! table)] ;; the ball was hit to this player
(.log js/console msg)
(<! (timeout 100)) ;; wait 100msecs
(>! table (update-in ball [:hits] inc)) ;; hit the ball back
(recur)))))
(defn game
[table ball]
(go (do (.log js/console "Game started.")
(>! table ball) ;; put the ball into play
(<! (timeout 1000)) ;; game lasts for ten seconds
(<! table) ;; take the ball out of play (fun police)
(.log js/console "Game ended."))))
(defn ping-pong!
[]
(let [table (chan)
ball {:hits 0}]
(player "ping" table) ;; start a player process that pings
(player "pong" table) ;; start a player process that pongs
(game table ball))) ;; start the game process
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment