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 executors:

(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)

notes

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

White

Quan

5 bài viết.
2 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
White
1 0
Crosssite scripting Injecting clientside scripts contain malicious content (e.g. steal cookies data) into web pages via: NonPersistent/Reflected...
Quan viết hơn 3 năm trước
1 0
Bài viết liên quan
White
0 4
fCC: Technical Documentation Page note So I have finished the HTML part of this exercise and I want to come here to lament about the lengthy HTML ...
HungHayHo viết 2 năm trước
0 4
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


White
{{userFollowed ? 'Following' : 'Follow'}}
5 bài viết.
2 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!