Created
July 27, 2019 18:57
-
-
Save tauzen/5627b073160bc08c2eff0c1e701f65ac to your computer and use it in GitHub Desktop.
7 languages in 7 weeks, Clojure day 3, sleeping barber
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
(def cut-count (atom 0)) | |
(def client-count (atom 0)) | |
(def cutting (atom false)) | |
(def client-approaching (atom false)) | |
(def client-queue (atom [])) | |
(defn cut [client-id] | |
(reset! cutting true) | |
(future | |
(Thread/sleep 20) | |
(reset! cut-count (inc @cut-count)) | |
(reset! cutting false))) | |
(defn incomming-client [queue client-id] | |
(if (< (count queue) 3) | |
(conj queue client-id) | |
queue)) | |
(defn remove-first-client [queue] | |
(if (> (count queue) 0) | |
(rest queue) | |
queue)) | |
(defn cut-next-client [] | |
(if (and (not @cutting) (> (count @client-queue) 0)) | |
(let [client-id (first @client-queue)] | |
(swap! client-queue remove-first-client) | |
(cut client-id)))) | |
(defn queue-clients [] | |
(if (not @client-approaching) | |
(do | |
(reset! client-approaching true) | |
(future | |
(Thread/sleep (+ 10 (rand-int 20))) | |
(reset! client-count (inc @client-count)) | |
(swap! client-queue incomming-client @client-count) | |
(reset! client-approaching false))))) | |
(defn get-time [] (System/currentTimeMillis)) | |
(defn time-up? [start-time] (> (System/currentTimeMillis) (+ start-time 10000))) | |
(defn start-loop [start-time] | |
(println "starting at" start-time) | |
(while (not (time-up? start-time)) | |
(do | |
(cut-next-client) | |
(queue-clients))) | |
(println "time elapsed " (- (get-time) start-time)) | |
(println "clients cut: " @cut-count ", overall clients: " @client-count)) | |
(start-loop (get-time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment