Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Last active November 12, 2017 09:29
Show Gist options
  • Select an option

  • Save lagenorhynque/00dd505e39956534db69f1d2065d4a7d to your computer and use it in GitHub Desktop.

Select an option

Save lagenorhynque/00dd505e39956534db69f1d2065d4a7d to your computer and use it in GitHub Desktop.
(ns channel-example
(:require [clojure.core.async :as async]))
(defn -main []
(let [ch1 (async/chan)
ch2 (async/chan)
ch3 (async/chan)]
(async/go-loop []
(let [i (async/<! ch1)]
(async/>! ch2 (* i 2))
(recur)))
(async/go-loop []
(let [i (async/<! ch2)]
(async/>! ch3 (- i 1))
(recur)))
(loop [n (atom 1)
continue? (atom true)]
(async/alt!!
[[ch1 @n]] (swap! n inc)
ch3 ([i] (println "received" i))
:default (when (> @n 100)
(reset! continue? false)))
(when @continue?
(recur n continue?)))))
package main
import (
"fmt"
)
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
ch3 := make(chan int)
go func() {
for {
i := <-ch1
ch2 <- (i * 2)
}
}()
go func() {
for {
i := <-ch2
ch3 <- (i - 1)
}
}()
n := 1
LOOP:
for {
select {
case ch1 <- n:
n++
case i := <-ch3:
fmt.Println("received", i)
default:
if n > 100 {
break LOOP
}
}
}
}
{:deps {org.clojure/clojure {:mvn/version "1.9.0-beta4"}
org.clojure/core.async {:mvn/version "0.3.443"}}
:paths ["."]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment