Skip to content

Instantly share code, notes, and snippets.

@tlonist-sang
Last active January 30, 2022 15:54
Show Gist options
  • Save tlonist-sang/06208cdc66dca22a473c2673fe947991 to your computer and use it in GitHub Desktop.
Save tlonist-sang/06208cdc66dca22a473c2673fe947991 to your computer and use it in GitHub Desktop.
async-test
(ns async-example
(:require [clojure.core.async :as a :refer [>! <! >!! <!! go chan buffer close! thread alts! alts!! put! timeout sliding-buffer]]
[clj-http.client :as client]
[cheshire.core :refer :all]))
(defn sample-request-async [x y c]
(let [response-cb (fn [response]
(go (>! c response)))
exception-cb (fn [^Throwable exception]
(println exception))]
(client/post
"http://localhost:3000/add"
{:form-params {:x x
:y y}
:async? true
:connection-timeout 2000}
response-cb
exception-cb)
c))
(defn sample-request [x y]
(client/post
"http://localhost:3000/add"
{:form-params {:x x
:y y}}))
(defn sample-request-mock [x y]
(Thread/sleep 1000)
(+ x y))
(comment
(doseq [_ (range 2)]
(prn (sample-request-mock (rand-int 100) (rand-int 100))))
;; use buffer
(time
(let [cs (chan 9999)]
(->> (for [x (range 9999)]
(do
(prn "Active thread =>" (Thread/activeCount))
(go (>! cs (sample-request-mock (rand-int 100) (rand-int 100))))))
(map (fn [_] (<!! cs)))
count)))
;; thread can use more threads than go-block
;; suitable for doing long blocking IOs
(time
(let [cs (chan 9999)]
(->> (for [x (range 9999)]
(do
(prn "Active thread =>" (Thread/activeCount))
(thread (>!! cs (sample-request-mock (rand-int 100) (rand-int 100))))))
(map (fn [_] (<!! cs)))
count))),)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment