class: center, middle, title title: Short Intro to core.async
Short Intro to core.async
- David Nolen - Clojure Library Core.async for Asynchronous Programming
- Timothy Baldridge - Clojure/conj 2013 talk on core.async
- Live coding in Emacs-live
-
Benjamin R. Haskell: Twitter @benizi, GitHub benizi
-
Day Job: Forever™ (mostly Ruby) --
-
#1 (tied) on 4clojure (quantity, not quality)
- Implementation of Communicating Sequential Processes (CSP)
- Provides a Channel abstraction
- Similar to how Go(lang) implemented Channels
- Works well in both Clojure and ClojureScript
;; in project.clj
(defproject my.project "0.1.0-SNAPSHOT"
;; ...
:dependencies [ ;; ...
[org.clojure/core.async "0.1.267.0-0d7780-alpha"] ;; ...
;; in your code that uses core.async
(ns my.project.core
(:require [core.async :as async
;; commonly:
:refer (go put! take!)]))
- You can create them
- without a buffer
(def a-channel (chan))
- with a buffer of size
n
chan(def a-channel (chan n))
- without a buffer
- You can close them
close!
(close! a-channel)
- You can put things onto them
- You can take things off of them
<iframe src="//clojure.github.io/core.async/index.html#clojure.core.async/go" scrolling="no" style="width: 80%; height: 10em; overflow: hidden"></iframe> --
Rewrites your code using crazy inversion-of-control macros, creating a state machine scaffolding for turning blocking takes/puts into parked, individual lightweight threads
- .strike[Rewrites your code using crazy inversion-of-control macros, creating a state machine scaffolding for turning blocking takes/puts into parked, individual lightweight threads]
- Allows you to write blocking code as if it weren't
(let [c (chan)] (go (println (<! c))) (go (>! c :some-value))) ;; => prints :some-value ;; despite the take appearing before the put
- Perform the next available operation on a set of channels
- Go(lang) select, similar to Linux select call
(def a (chan)) (def b (chan)) (put! a 42) (alts!! [a b])
- alts! - in a go block
- alts!! - outside
- Times out after n milliseconds
- Useful with alts!/alts!!
(let [c (chan) t (timeout 100)] (let [[v ch] (alts!! [c t])] (prn {:ch ch :v v})))
- When full, puts can complete, but won't have any effect
(async/dropping-buffer n)
- When full, puts can complete, but first item still in the channel is dropped
(async/sliding-buffer n)