philipbohun.com

Glojure by Example: Channels

clojure.core.async is the channel library. Its channels are Go channels, and its go blocks run on goroutines. chan creates a channel. >! sends and <! receives. In Glojure those operations block the goroutine, so they behave like >!! and <!! on the JVM.

(require '[clojure.core.async :as async])

(def messages (async/chan))
(async/go (async/>! messages "ping"))
(println (async/<! messages))

An unbuffered send waits until someone receives. nil is not a valid message: a nil receive means the channel was closed.

(def pings (async/chan))
(async/go
  (println "send" (async/>! pings "pong")))
(println "recv" (async/<! pings))

The send and the receive meet on the channel.

$ glj channels.glj
ping
send true
recv pong

Next example: Channel Buffering.