Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Andrey Paramonov
committed
Oct 7, 2012
1 parent
6acbc07
commit 9566196
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
;; http://en.wikipedia.org/wiki/Dining_philosophers_problem | ||
|
||
(ns dojo.philosophers) | ||
|
||
(defn forks [n] (mapv ref (repeat n 0))) | ||
|
||
(defn enjoy-meal [] (Thread/sleep (rand-int 500))) | ||
|
||
(defn eat [phil forks] | ||
(let [place (map #(mod % (count forks)) [phil (inc phil)])] | ||
(dosync | ||
(alter (forks (first place)) inc) ; grab right fork | ||
(alter (forks (second place)) inc) ; grab left fork | ||
(enjoy-meal)))) | ||
|
||
(defn log [thread & message] | ||
(println (System/currentTimeMillis) ":" (inc thread) message)) | ||
|
||
(defn think [] (Thread/sleep (rand-int 500))) | ||
|
||
(defn philosopher [id meals forks] | ||
(dotimes [m meals] | ||
(log id "thinking") | ||
(think) | ||
(log id "hungry") | ||
(eat id forks) | ||
(log id "ate" (inc m) "meal"))) | ||
|
||
(defn dine | ||
([people meals] | ||
(dine people meals (forks people))) | ||
([people meals forks] | ||
(let [threads (map (fn [id] #(philosopher id meals forks)) (range people))] | ||
(dorun (apply pcalls threads))))) | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
(ns dojo.philosophers-test | ||
(:use clojure.test | ||
dojo.philosophers)) | ||
|
||
(deftest eat-test | ||
(let [forks (forks 5)] | ||
(eat 0 forks) | ||
(is (= [1 1 0 0 0] (mapv deref forks))) | ||
(eat 1 forks) | ||
(is (= [1 2 1 0 0] (mapv deref forks))))) | ||
|
||
(comment deftest philosopher-test | ||
(let [forks (forks 5)] | ||
(philosopher 0 7 forks) | ||
(is (= [7 7 0 0 0] (mapv deref forks))))) | ||
|
||
(deftest dine-test | ||
(let [forks (forks 5)] | ||
(dine 5 3 forks) | ||
(is (= [6 6 6 6 6] (mapv deref forks))))) | ||
|