Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
pmap using core.async
(ns async-example.core
(:require [clojure.core.async :refer :all])
(:gen-class))
(defn my-pmap [f col]
(let [chans (repeatedly (count col) chan)]
(doseq [[c e] (map vector chans col)]
(go (>! c (f e))))
(map <!! chans)))
(defn -main [& args]
(println (my-pmap (fn [x] (Thread/sleep 1000) (identity x)) (range 0 10))))
time lein run
(0 1 2 3 4 5 6 7 8 9)
lein run 3.33s user 0.26s system 71% cpu 5.046 total
@sherpc

This comment has been minimized.

Copy link

@sherpc sherpc commented Oct 3, 2017

It can be simpler:

(defn map-async
  [f coll]
  (->>
   coll
   (map (fn [x] (async/go (f x))))
   (doall)
   (map async/<!!)))

Remember that in both variants all exceptions during (f x) will be remain in go blocks, so you need carefully handle this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment