【问题标题】:Agents and threads synchronization in ClojureClojure 中的代理和线程同步
【发布时间】:2019-04-08 01:00:30
【问题描述】:

我必须以某种方式使用代理重写此代码 x 的结果为 0(这意味着每个线程一个接一个地执行)。但是我有问题,因为我对代理的使用没有足够的了解。 原代码为:

(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))

当我想使用带有await(agent_name) 的代理让每个线程单独运行时,它不起作用,结果总是不为零。 请问有什么建议吗?

【问题讨论】:

    标签: multithreading join concurrency clojure


    【解决方案1】:

    我试了一下,它按预期打印了0

    (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)))
    

    【讨论】:

    • 谢谢我的朋友,我被这个问题困住了。 :D
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2015-05-22
    相关资源
    最近更新 更多