QuanNH
QuanNH

Reputation: 419

Concurrent process in Clojure

I have a list of item [1 2 3 4 5 ..] and a function process on it (defn process[conn i] ..).

How can i apply this function to all item of the list concurrently, but limit number of processes at the same time (e.g. only 2 processes run at a time). And when all processes completed, I was notify so that i can cleanup resources (close conn, etc.).

Thanks,

Upvotes: 0

Views: 133

Answers (1)

Alex Miller
Alex Miller

Reputation: 70211

You could just use the built-in Java executors:

(defn process [conn i]
  (println (str "Thread " (.getName (Thread/currentThread)) " executing " i "\n")))

(defn execute [data conn]
  (let [svc (java.util.concurrent.Executors/newFixedThreadPool 2)
        jobs (map (fn [v] #(process conn v)) data)]
    (.invokeAll svc jobs)))

(execute (range 100) nil)

Here execute will return a list of completed Futures with the results of each job (which may be either success or failure).

Upvotes: 5

Related Questions