Last active
December 17, 2024 12:13
-
-
Save kumar88kanishk/5a47fc9c4a323c4aa8d17d29bceb82e2 to your computer and use it in GitHub Desktop.
Core.aysnc exercise
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
(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) | |
) |
Author
kumar88kanishk
commented
Dec 17, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment