Clojure core.async, any way to control number of threads in that (go…) thread pool?

后端 未结 2 1604
故里飘歌
故里飘歌 2020-12-29 15:26

By default (go..) will use twice the number of cores + 42 threads for the thread pool. Is there any way I can set the number of threads, or number of CPUs that the code can

2条回答
  •  醉梦人生
    2020-12-29 15:56

    The current accepted answer was valid up to this commit so basically now you have two cases:

    • If you want to just change the max number of threads in the pool, you pass the number as Java property clojure.core.async.pool-size (it defaults to 8)

    • If you want to replace the ExecutorService, you use the same trick of alter-var-root but targeting the new implementation (there a protocol to implement):

      (ns your-app.threadpool
        (:require [clojure.core.async.impl.protocols :as protocols]
                  [clojure.core.async.impl.concurrent :as conc]
                  [clojure.core.async.impl.exec.threadpool :as tp])
        (:import java.util.concurrent.Executors))
      
      (defonce my-executor
        (let [executor-svc (Executors/newFixedThreadPool
                            1
                            (conc/counted-thread-factory "async-dispatch-%d" true))]
          (reify protocols/Executor
             (protocols/exec [this r]
               (.execute executor-svc ^Runnable r)))))
      
      (alter-var-root #'clojure.core.async.impl.dispatch/executor
                      (constantly (delay my-executor)))
      

提交回复
热议问题