Core.Async – For Me and You – Clojure Intro: Data Types



Core.Async – For Me and You – Clojure Intro: Data Types

0 0


async_presentation


On Github AshtonKem / async_presentation

Core.Async

For Me and You

Ashton A. Kemerling

What is Clojure?

  • (originally) JVM based Lisp Language.
  • Not CL-Hyperspec compatible
  • Hygenic Macros
  • Emphasis on Immutability and Thread Safety
  • Compilers for JS, C, and .NET

Clojure Intro: Data Types

  • Lists
    • (list 1 2 3)
    • '(1 2 3)
  • Vectors
    • (vec 1 2 3)
    • [1 2 3]
  • Maps
    • (hash-map :a 1 :b 2)
    • {:a 1 :b 2}
  • Sets
    • (hash-set 1 2 3)
    • #{1 2 3}

Clojure Intro: Functions

Defining Functions.

(defn fib [x]
  (if (<= x 0)
      1
      (* x (fib (- x 1))))))

Calling Functions.

(fib 24)

Clojure Intro: Variables

(defn fib [x]
  (let [positive? (>= x 0)
        sub-call (fib (- x 1))]
    (if positive?
        (* x sub-call)
        1)))

All variables are immutable. Re-defining them in the let block shadows previous definition.

What is Core.Async?

  • Go Style CSP channels for Clojure
  • Provided by a library, not the language
  • Works for Clojure & Clojurescript
  • Native threads not required

Creating Channels

Channels can be configured, but they are untyped

  • No argument, unbuffered
  • Number argument creates a fixed buffer of a given size
  • Optionally provide a buffer object, like dropping-buffer or sliding-buffer

Adding and Removing Items

Two kinds of operations, blocking and parking

  • Blocking operations block the current thread
  • Parking operations execute the block with a pool of threads
  • Parking operations must be executed inside a go block

Insertions

  • >!! - Blocking operation
  • >! - Parking operation

Removals

  • <!! - Blocking operation
  • <! - Parking operation

Go BLocks

  • Enables single/multi thread blocking (parking) operations
  • All parking operations must be in a go block
(let [c1 (chan)
      c2 (chan)]
    (go (while true
          (let [[v ch] (alts! [c1 c2])]
            (println "Read" v "from" ch))))
            (go (>! c1 "hi"))
            (go (>! c2 "there")))

Multiple Channels

The alts! and alts!! methods can select from multiple channels. Used to replace the select idiom from Go

(let [c1 (chan)
      c2 (chan)]
  (thread (while true
            (let [[v ch] (alts!! [c1 c2])]
              (println "Read" v "from" ch))))
  (>!! c1 "hi")
  (>!! c2 "there"))

Demo!

Courtesy of Swannodette

10,000 Processes