Skip to content

Instantly share code, notes, and snippets.

@tauzen
Created July 27, 2019 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tauzen/5627b073160bc08c2eff0c1e701f65ac to your computer and use it in GitHub Desktop.
Save tauzen/5627b073160bc08c2eff0c1e701f65ac to your computer and use it in GitHub Desktop.
7 languages in 7 weeks, Clojure day 3, sleeping barber
(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