Created
September 19, 2012 18:28
-
-
Save devnoo/3751306 to your computer and use it in GitHub Desktop.
seven languages in seven weeks: clojure day 3
This file contains hidden or 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
(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) |
This file contains hidden or 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
(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