Skip to content

Instantly share code, notes, and snippets.

@cgrand
Created September 18, 2009 10:33
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 cgrand/189002 to your computer and use it in GitHub Desktop.
Save cgrand/189002 to your computer and use it in GitHub Desktop.
;; a better version of http://bestinclass.wordpress.com/2009/09/17/scala-vs-clojure-round-2-concurrency/
(def empty-seats (ref 3))
(def barber (agent 0))
(defn debug [msg n]
(println msg (apply str (repeat (- 35 (count msg)) \space)) n)
(flush))
(defn cut-hair [tally n]
(dosync (commute empty-seats inc))
(debug "(b) cutting hair of customer" n)
(Thread/sleep (+ 100 (rand-int 600)))
(debug "(b) done cutting hair of customer" n)
(inc tally))
(defn enter-the-shop [n]
(debug "(c) entering shop" n)
(when-not (dosync
(when (pos? @empty-seats)
(alter empty-seats dec)
(send-off barber cut-hair n)))
(debug "(s) turning away customer" n)))
(doseq [customer (range 1 20)]
; (Thread/sleep (+ 100 (rand-int 200)))
(future (enter-the-shop customer)))
(Thread/sleep 2000)
(println "(!) " @barber "customers got haircuts today")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment