Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,30 @@
(defn make-fork []
(ref true))
(defn make-philosopher [name forks food-amt]
(ref {:name name :forks forks :eating? false :food food-amt}))
(defn start-eating [phil]
(dosync
(if (every? true? (map ensure (:forks @phil))) ; <-- the essential solution
(do
(doseq [f (:forks @phil)] (alter f not))
(alter phil assoc :eating? true)
(alter phil update-in [:food] dec)
true)
false)))
(defn stop-eating [phil]
(dosync
(when (:eating? @phil)
(alter phil assoc :eating? false)
(doseq [f (:forks @phil)] (alter f not)))))
(defn dine [phil retry-interval max-eat-duration max-think-duration]
(while (pos? (:food @phil))
(if (start-eating phil)
(do
(Thread/sleep (rand-int max-eat-duration))
(stop-eating phil)
(Thread/sleep (rand-int max-think-duration)))
(Thread/sleep retry-interval))))

View file

@ -0,0 +1,20 @@
(def *forks* (cycle (take 5 (repeatedly #(make-fork)))))
(def *philosophers*
(doall (map #(make-philosopher %1 [(nth *forks* %2) (nth *forks* (inc %2))] 1000)
["Aristotle" "Kant" "Spinoza" "Marx" "Russell"]
(range 5))))
(defn start []
(doseq [phil *philosophers*]
(.start (Thread. #(dine phil 5 100 100)))))
(defn status []
(dosync
(doseq [i (range 5)]
(let [f @(nth *forks* i)
p @(nth *philosophers* i)]
(println (str "fork: available=" f))
(println (str (:name p)
": eating=" (:eating? p)
" food=" (:food p)))))))