我有一个练习:
Print in order all positive integers from 1 to 100.
Using blocks, semaphores or other similar mechanisms (but avoiding sleep), coordinate two threads such that the combined output from both threads appears in numerical order.
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找到了这个示例,现在我正在尝试将其翻译成Clojure。