Last active
February 11, 2016 11:01
-
-
Save swannodette/5903001 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; based on http://talks.golang.org/2012/concurrency.slide#50 | |
(ns robpike | |
(:require [cljs.core.async :as async :refer [<! >! chan close!]]) | |
(:require-macros [cljs.core.async.macros :as m :refer [go alt!]])) | |
(defn timeout [ms] | |
(let [c (chan)] | |
(js/setTimeout (fn [] (close! c)) ms) | |
c)) | |
(defn fake-search [kind] | |
(fn [c query] | |
(go | |
(<! (timeout (rand-int 100))) | |
(>! c [kind query])))) | |
(def web1 (fake-search :web1)) | |
(def web2 (fake-search :web2)) | |
(def image1 (fake-search :image1)) | |
(def image2 (fake-search :image2)) | |
(def video1 (fake-search :video1)) | |
(def video2 (fake-search :video2)) | |
(defn fastest [query & replicas] | |
(let [c (chan)] | |
(doseq [replica replicas] | |
(replica c query)) | |
c)) | |
(defn google [query] | |
(let [c (chan) | |
t (timeout 80)] | |
(go (>! c (<! (fastest query web1 web2)))) | |
(go (>! c (<! (fastest query image1 image2)))) | |
(go (>! c (<! (fastest query video1 video2)))) | |
(go (loop [i 0 ret []] | |
(if (= i 3) | |
ret | |
(recur (inc i) (conj ret (alt! [c t] ([v] v))))))))) | |
(go (println (<! (google "clojure")))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment