1

I am wondering why data from a core.async channel is retrieved by a pull mechanism in a endless loop. For example:

user=> (def c (chan 1))
#'user/c

user=> (go-loop []
         (let [x (<! c)]
           (println "Got a value in this loop:" x))
         (recur))

#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@30df0e27>

ref: https://clojuredocs.org/clojure.core.async/go-loop#example-542c88e3e4b05f4d257a297b

Why isn't there a push mechanism which I could hook onto? Or why isn't such a loop some implementation detail of core.async subscriber? I think having a mechanism running endlessly is very cpu consuming. Is this not the case?

1 Answer 1

2

The docstring for core.async/go says:

Asynchronously executes the body, returning immediately to the calling thread. Additionally, any visible calls to ! and alt!/alts! channel operations within the body will block (if necessary) by 'parking' the calling thread rather than tying up an OS thread (or the only JS thread when in ClojureScript). Upon completion of the operation, the body will be resumed. Returns a channel which will receive the result of the body when completed

If go didn't park when it was waiting for new messages on the queue, then looping would indeed be very wasteful on the CPU. However, when the go loop reaches <! it will park the thread and will only resume when a value is available to take from the queue.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.