简体   繁体   中英

Can I deref futures/promises in clojure.core.async/go?

I'm trying to find a way to harmlessly observe many future s. By that, I mean without blocking N threads to wait for N future s.

I see that core.async library is build in a way it doesn't block thread with blocking operations, but rather park it and reuse the thread. Is it the case with deref, or it works only with <! and alts! ?

the future-done? function can be used to poll an array of futures to see which ones are ready to be looked at:

main> (future-done? (future 42))
true
main> (future-done? (future (Thread/sleep 1000) 42))
false

you can then create a function that polls all the futures (in a vector perhaps) for one to work on, then goes and does the work. this way instead of blocking a thread on each future, you block a thread on any future and decide how many such workers you want (one at a time is a common choice)

If you want it to be more efficient, or more expressive, than this you would be creating a state machine to track which futures to check and work on which would put you on the path to recreate your own version clojure.core.async/alts! and might do better to use core.async all the way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM