Skip to content

Instantly share code, notes, and snippets.

@jezen
Created August 4, 2014 21:06
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 jezen/22f23e394a90c4dc56d8 to your computer and use it in GitHub Desktop.
Save jezen/22f23e394a90c4dc56d8 to your computer and use it in GitHub Desktop.
Barber…
(ns barber.core
(:gen-class))
(def chair (ref []))
(def lost-customers (ref []))
(def shop-is-open (ref false))
(def serviced-customers (ref []))
(def waiting-customers (ref clojure.lang.PersistentQueue/EMPTY))
; If there are less than three customers waiting for a haircut, we can welcome
; them in and sit them down. If there are already three customers waiting, the
; barber has lost some business.
(defn greet-customer [customer]
(dosync
(if (< (count @waiting-customers) 3)
(alter waiting-customers conj customer)
(alter lost-customers conj customer))))
; Take a customer and cut his hair for 20 milliseconds. Once we’re done, we add
; him to our list of satisfied customers.
(defn cut-hair [customer]
(do
(Thread/sleep 20)
(dosync (alter serviced-customers conj customer))))
; While the shop is open, continuously check the waiting room for waiting
; customers. If we find one, remove him from the waiting room and send him to
; have his hair cut.
(defn monitor-waiting-room []
(while @shop-is-open
(if (not (empty? @waiting-customers))
(do
(cut-hair (first @waiting-customers))
(dosync (alter waiting-customers pop))))))
(defn send-customers-from-street []
(while @shop-is-open
(do
(Thread/sleep (+ 10 (rand-int 21)))
(greet-customer :customer))))
(defn open-for-business []
(do
(dosync (ref-set shop-is-open true))
(monitor-waiting-room)
(send-customers-from-street)
(Thread/sleep (* 10 1000))
(dosync (ref-set shop-is-open false))))
(open-for-business)
(println "serviced customers: " (count @serviced-customers))
(println "lost customers: " (count @lost-customers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment