Skip to content

Instantly share code, notes, and snippets.

@LauJensen
Created September 17, 2009 12:00
Show Gist options
  • Save LauJensen/188459 to your computer and use it in GitHub Desktop.
Save LauJensen/188459 to your computer and use it in GitHub Desktop.
(def queue (ref (with-meta
clojure.lang.PersistentQueue/EMPTY
{:tally 0})))
(def seats 3)
(defn debug
[msg n]
(println msg (apply str (repeat (- 35 (count msg)) \space)) n)
(flush))
(defn the-shop
[a]
(debug "[c] entering shop" a)
(dosync
(if (< (count @queue) seats)
(alter queue conj a)
(debug "[s] turning away customer" a))))
(defn the-barber
[st q]
(Thread/sleep (+ 100 (rand-int 300)))
(dosync
(when (peek @q)
(debug "[b] cutting hair of customer" (peek @q))
(ref-set queue (with-meta (pop @q)
{:tally (inc (:tally (meta @q)))})))))
(add-watcher queue :send (agent 'barber) the-barber)
(doseq [customer (range 1 20)]
(Thread/sleep (+ 100 (rand-int 200)))
(send-off (agent customer) the-shop))
(Thread/sleep 2000)
(println "[!] " (:tally (meta @queue)) "customers got haircuts today")
=====>
[c] entering shop 1
[c] entering shop 2
[c] entering shop 3
[b] cutting hair of customer 1
[b] cutting hair of customer 2
[c] entering shop 4
[c] entering shop 5
[b] cutting hair of customer 3
[c] entering shop 6
[b] cutting hair of customer 4
[c] entering shop 7
[c] entering shop 8
[s] turning away customer 8
[b] cutting hair of customer 5
[b] cutting hair of customer 6
[c] entering shop 9
[c] entering shop 10
[c] entering shop 11
[s] turning away customer 11
[b] cutting hair of customer 7
[c] entering shop 12
[b] cutting hair of customer 9
[c] entering shop 13
[c] entering shop 14
[s] turning away customer 14
[b] cutting hair of customer 10
[b] cutting hair of customer 12
[c] entering shop 15
[b] cutting hair of customer 13
[c] entering shop 16
[b] cutting hair of customer 15
[c] entering shop 17
[b] cutting hair of customer 16
[c] entering shop 18
[b] cutting hair of customer 17
[c] entering shop 19
[b] cutting hair of customer 18
[b] cutting hair of customer 19
[!] 16 customers got haircuts today
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment