Kevin Zhu
Kevin Zhu

Reputation: 2836

Clojure core.async, what's the difference between putting (go... ) block inside (doseq ..) and putting it outside?

I've read this article about core.async and learned < ! ! is used to block main thread until go block returns last channel. In the original example, < ! ! and go block is inside (doseq...), is it OK if they are put outside ? Looks like they behave the same.

;;original example code 
(let [c (chan)]
  (doseq [i (range 10)]
    (go
     (Thread/sleep  1000)
     (>! c i)))

  (doseq [_ (range 10)]
    (<!!
     (go
      (println (<! c))))))

;;putting <!! part outside doseq 
(let [c (chan)]
  (doseq [i (range 10)]
    (go
     (Thread/sleep  1000)
     (>! c i)))

  (<!!
   (go
    (doseq [_ (range 10)]
      (println (<! c))))))

Upvotes: 2

Views: 929

Answers (1)

cgrand
cgrand

Reputation: 7949

Since <!! is blocking, the doseq will wait for the previous go block to be over before starting another one. So it's very serial. By putting the doseq in the go you just move where the code is executed and it doesn't change the serial nature of this code.

In truth since it's blocking and serial you could as well get rid of the go and just:

(doseq [_ (range 10)]
      (println (<!! c))

Upvotes: 2

Related Questions