【发布时间】:2023-04-01 19:53:01
【问题描述】:
我有一个练习:
按顺序打印从 1 到 100 的所有正整数。
-
使用块、信号量或其他类似机制(但避免休眠)协调两个线程,以便两个线程的组合输出按数字顺序显示。
Sample Output In thread one: The number is ‘1’ In thread two: The number is ‘2’ In thread one: The number is ‘3’ In thread two: The number is ‘4’
该练习适用于 Ruby,但我想向我的班级展示 Clojure 可能是该任务的不错选择。
我对任何语言的线程都没有任何经验,但我想使用类似的东西:
(def thread_1 (future (swap! my-atom inc) ))
(def thread_2 (future (swap! my-atom inc) ))
但 @thread_1 总是返回相同的值。有没有办法在 Clojure 中协调两个线程?
我在 Java 中使用 ReentrantLock 和 Condition 找到了这个 example,现在我正在尝试将它翻译成 Clojure。
【问题讨论】:
-
顺序重要吗?我的意思是线程应该一个接一个地工作,就像你的例子一样。
-
@fl00r,是的,顺序必须是连续的。
标签: multithreading clojure clojure-java-interop