I’ve been experimenting with Clojure’s multithreading features lately and trying to implement a simple concurrency problem. In the code below I run function write with one agent and try to send a job to another agent, but the program blocks at this line:
(doseq [j (range (count readers))]
(send (nth readers j) rr (inc j)))
Complete code:
(def state (ref 0))
(def readers (doall (map #(agent %) (repeat 3 0))))
(def writers (doall (map #(agent %) (repeat 3 0))))
(defn rr [re]
(println (format "Read about %s" @state))
(inc re)
)
(defn write [re topic]
(dosync
(ref-set state topic)
)
(Thread/sleep (rand-int 1000))
(println "Wrote about" topic)
(doseq [j (range (count readers))]
(send (nth readers j) rr (inc j)))
(inc re)
)
(defn -main[]
(dotimes [i 5]
(doseq [j (range (count writers))]
(send (nth writers j) write (inc j))))
(dorun (map #(await %) writers))
(dorun (map #(println "Writes:" @%) writers))
)
I’m not totally sure what you’re trying to do but the function
rris defined to take one argument but according toit should actually have to take two arguments (the first being the current value of the agent and the second argument is the value of
(inc j).The expression
(agent-error (first writers))should reveal some kind of Arity exception (though I haven’t tried it)