Skip to content

Instantly share code, notes, and snippets.

@jezen
Created August 4, 2014 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jezen/33550ae8fac8df1eb2e4 to your computer and use it in GitHub Desktop.
Save jezen/33550ae8fac8df1eb2e4 to your computer and use it in GitHub Desktop.
Sleeping 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))))
(defn open-for-business
(do
(dosync (ref-set shop-is-open true))
(Thread/sleep (* 10 100))
(dosync (ref-set shop-is-open false))))
; 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.
(while @shop-is-open
(if (not (empty? @waiting-customers))
(do
(cut-hair (first @waiting-customers))
(dosync (alter waiting-customers pop)))))
(while true
(do
(Thread/sleep (+ 10 (rand-int 21)))
(greet-customer :customer)))
(open-for-business)
(println @serviced-customers)
(println @lost-customers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment