2

I have to rewrite this code using agents in someway the result of x is 0 (It means that each thread is executed one after one). But I have problems because I do not have enough knowledge about agents use. The original code is:

(def x 0) (let [t1 (Thread. #(dotimes [_ 10000] (def x (inc x)))) t2 (Thread. #(dotimes [_ 10000] (def x (dec x))))] (.start t1) (.start t2) (.join t1) (.join t2) (println x)) 

When I want to use an agent with await(agent_name) to make each thread run separately, it does not work, the result is always different from zero. Please any suggestions about this?

1 Answer 1

4

I gave this a try and it prints 0 as expected:

(ns agent-demo.core (:gen-class)) (def counter (agent 0)) (defn -main [& args] (let [t1 (Thread. #(dotimes [_ 10000] (send counter inc))) t2 (Thread. #(dotimes [_ 10000] (send counter dec)))] (.start t1) (.start t2) (.join t1) (.join t2) (await counter) (println @counter) (shutdown-agents))) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks my friend, I was stuck in this question. :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.