Skip to content

Instantly share code, notes, and snippets.

@devnoo
Created September 19, 2012 18:28
Show Gist options
  • Save devnoo/3751306 to your computer and use it in GitHub Desktop.
Save devnoo/3751306 to your computer and use it in GitHub Desktop.
seven languages in seven weeks: clojure day 3
(def accounts (ref []))
(defn openaccount [] (dosync (alter accounts conj 0)))
(defn debit [ accountnr debitammount] (dosync (alter accounts #(assoc %1 accountnr (- (get %1 accountnr) debitammount)))))
(defn credit [ accountnr creditammount] (dosync (alter accounts #(assoc %1 accountnr (+ creditammount (get %1 accountnr) )))))
(openaccount)
(println @accounts)
(credit 0 100)
(println @accounts)
(credit 0 100)
(println @accounts)
(println @accounts)
(debit 0 100)
(println @accounts)
(def waiting-customers (atom 0))
(def waiting-room-size 3)
(def number-of-haircuts (atom 0))
(def open? (atom true))
(defn open-shop [duration]
(future
(println "opening shop")
(Thread/sleep (* 1000 duration ))
(swap! open? not)
(println "closing shop")
)
)
(defn spawn-customers []
(future
(while @open?
(if ( < @waiting-customers waiting-room-size )
(do
(println "entering")
(swap! waiting-customers inc)
(Thread/sleep (+ 10 (rand-int 20)))
)
)
)
)
)
(defn gotowork []
(future
(while @open?
(if (> @waiting-customers 0 )
(do
(println "cutting")
(swap! waiting-customers dec)
(swap! number-of-haircuts inc)
(Thread/sleep 20)
)
)
)
)
)
(def shopthread (open-shop 10))
(spawn-customers )
(gotowork)
(deref shopthread )
(println @number-of-haircuts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment