Bạn có chắc chắn muốn xóa bài viết này không ?
ThreadPool in Clojure
Clojure supports flexible concurrency models for real world complexity:
- STM: built-in support.
- CSP: similar to Golang concurrency model, with help of core.async library.
- Actor: using Pulsar library, similar to Erlang Actor & Akka in Scala.
Sometimes, we just want to run some simple tasks in parallel & control its level of parallelism. It could be done using the built-in Java
(import '(java.util.concurrent Executors)) (defn process [i] (str "Thread " (.getName (Thread/currentThread)) " executing " i)) (defn execute [data] (let [pool (Executors/newFixedThreadPool 2) tasks (map (fn [v] #(process v)) data)] (doseq [future (.invokeAll pool tasks)] (println (.get future))) (.shutdown pool))) (execute (range 100))
Using climate/claypoole library
(require '[com.climate.claypoole :as cp]) ;; Use a temporary threadpool with 4 threads. (cp/pmap 4 myfunction myinput) ;; Use a temporary threadpool with ncpus + 2 threads. (cp/pmap (+ 2 (cp/ncpus)) myfunction myinput)
java.util.concurrent.Callable, so we can pass it to
- Introduction to Java Concurrency Executors, Java Thread Pool Example, Java 8 Concurrency Tutorial: Threads and Executors