Created
September 18, 2009 10:33
-
-
Save cgrand/189002 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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