Created
December 5, 2013 20:45
-
-
Save geoffrys/7813558 to your computer and use it in GitHub Desktop.
Minimal Dining Philosophers (http://en.wikipedia.org/wiki/Dining_philosophers_problem)
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 place-settings 5) | |
(def chopsticks (repeatedly place-settings #(ref true))) | |
(def philosophers (map #(agent %) (partition 2 1 chopsticks chopsticks))) | |
(defn sleep [] (Thread/sleep (rand-int 1000))) | |
(def eat sleep) | |
(def think sleep) | |
(defn toggle-chopsticks [cs pred?] | |
(dosync | |
(when (pred? cs) | |
(doseq [c cs] (alter c not)) | |
true))) | |
(defn get-chopsticks [cs] (toggle-chopsticks cs #(every? ensure %))) | |
(defn release-chopsticks [cs] (toggle-chopsticks cs (constantly true))) | |
(defn dine [cs] | |
(when (get-chopsticks cs) | |
(eat) | |
(release-chopsticks cs)) | |
(think) | |
(send-off *agent* dine) | |
cs) | |
(doseq [p philosophers] | |
(send-off p dine)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment