如何使用ref,agent和future在clojure中编写并发程序?

时间:2013-11-25 20:50:04

标签: clojure

我正在编写一个程序,允许两个期货从账户A转账到账户B.每个未来都会尝试转移金额并在此之后休息一段时间。我的程序编译时没有错误,所以我不知道从哪里开始调试它。它应该打印出文本,但事实并非如此。有人能告诉我我的程序发生了什么吗?

   ;here are initial amounts of balance A and B
   (def balanceA {ref 1000})
   (def balanceB {ref 2000})

   ;agent will count a number of complete transfer
   (def agentCount {agent 1})

   ; this func will do the transfer with the waitingTime/sleep
   (defn transfer [balanceA balanceB amount futureNum waitingTime]
    )

   ; Two futures will repeat 10 times doing the transactions and print out the balances
   (dotimes [n 10](def futureA (future transfer(balanceA balanceB 20 1 (rand-int 100)) (prn "result" @balanceA @balanceB))))

   (dotimes [n 10](def futureB (future transfer(balanceA balanceB 15 2 (rand-int 40))(prn "result" @balanceA @balanceB))))

   (shutdown-agents)

1 个答案:

答案 0 :(得分:2)

更新:感谢@noisesmith评论/更正!

只有您的转接电话中有一个移位的括号,并且您的裁判和代理人定义上有错误

错误定义:{ref 1000}或{agent 1}而不是(ref 1000)(代理1)     (def balanceA(ref 1000))     (def balanceB(ref 2000))     (def agentCount(代理1))

和括号......

(未来转移 balanceA ... =>(未来转移余额A ...

你必须改变这个:

   (dotimes [n 10](def futureA (future transfer(balanceA balanceB 20 1 (rand-int 100)) (prn "result" @balanceA @balanceB))))

   (dotimes [n 10](def futureB (future transfer(balanceA balanceB 15 2 (rand-int 40))(prn "result" @balanceA @balanceB))))

有了这个:

   (dotimes [n 10](def futureA (future (transfer balanceA balanceB 20 1 (rand-int 100)) (print "result" @balanceA @balanceB))))

   (dotimes [n 10](def futureB (future (transfer balanceA balanceB 15 2 (rand-int 40))(prn "result" @balanceA @balanceB))))