Skip to content

Instantly share code, notes, and snippets.

@kumar88kanishk
Last active December 17, 2024 12:13
Show Gist options
  • Save kumar88kanishk/5a47fc9c4a323c4aa8d17d29bceb82e2 to your computer and use it in GitHub Desktop.
Save kumar88kanishk/5a47fc9c4a323c4aa8d17d29bceb82e2 to your computer and use it in GitHub Desktop.
Core.aysnc exercise
(ns burgershop
(:require [clojure.core.async :as a]))
;; This exercise simulates a burger shop.
;; Workers for a burger shop
;; They take one item from in channel, do some operations (put bun/split bun/etc) and put the result in next channel
;; Running flag for system to stop
(defn w1 [out running?]
(a/go-loop []
(a/>! out ["bun" (System/currentTimeMillis)])
(a/<! (a/timeout 100))
(if @running?
(recur)
(a/close! out))))
(defn w2 [in out]
(a/go-loop [x (a/<! in)]
(if x
(do
(a/<! (a/timeout 500))
(a/>! out (conj x "split-bun"))
(recur (a/<! in)))
(a/close! out))))
(defn w3 [in out]
(a/go-loop [x (a/<! in)]
(if x
(do
(a/<! (a/timeout 2000))
(a/>! out (conj x "put-patty"))
(recur (a/<! in)))
(a/close! out))))
(defn w4 [in]
(a/go-loop [x (a/<! in)]
(when x
(println (conj x "assemble-burger") (- (System/currentTimeMillis) (second x)))
(recur (a/<! in)))))
;; 3 Queues being shared with 4 workers
(defn system [running?]
(let [q1 (a/chan 1)
q2 (a/chan 1)
q3 (a/chan 1)]
(w1 q1 running?)
;; Increase workers for performance
(dotimes [_ 5]
(w2 q1 q2))
(dotimes [_ 20]
(w3 q2 q3))
(w4 q3)))
(comment
(def running? (atom true))
(system running?)
(reset! running? false)
)
@kumar88kanishk
Copy link
Author

Screenshot 2024-12-17 at 5 32 09 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment