[英]Clojure core.async, any way to control number of threads in that (go…) thread pool?
By default (go..) will use twice the number of cores + 42 threads for the thread pool.默认情况下 (go..) 将为线程池使用两倍的内核数 + 42 个线程。 Is there any way I can set the number of threads, or number of CPUs that the code can use, through setting an environment variable or sth?
有什么办法可以通过设置环境变量或某事来设置代码可以使用的线程数或CPU数吗?
On linux machine I can set number of CPU using taskset , eg taskset -c 0,1 my_Java_or_Clojure_program
, although taskset seems not effective on the number returned by (-> (java.lang.Runtime/getRuntime) .availableProcessors)
.在 linux 机器上,我可以使用taskset设置 CPU 数量,例如
taskset -c 0,1 my_Java_or_Clojure_program
,尽管 taskset 似乎对(-> (java.lang.Runtime/getRuntime) .availableProcessors)
返回的数字(-> (java.lang.Runtime/getRuntime) .availableProcessors)
。
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)如果您只想更改池中的最大线程数,则将该数字作为 Java 属性
clojure.core.async.pool-size
传递(默认为 8)
If you want to replace the ExecutorService
, you use the same trick of alter-var-root
but targeting the new implementation (there is a protocol to implement):如果您想替换
ExecutorService
,您可以使用与alter-var-root
相同的技巧,但要针对新的实现(有一个要实现的协议):
(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)))
In the current Clojure version of core.async, the thread pool executor is located in the clojure.core.async.impl.dispatch
namespace.在 core.async 的当前 Clojure 版本中,线程池执行器位于
clojure.core.async.impl.dispatch
命名空间中。 You can alter the executor
var and supply a custom thread pool ExecutorService
.您可以更改
executor
var 并提供自定义线程池ExecutorService
。
(ns sandbox
(:require [clojure.core.async.impl.concurrent :as conc]
[clojure.core.async.impl.exec.threadpool :as tp]
[clojure.core.async :as async]))
(defonce my-executor
(java.util.concurrent.Executors/newFixedThreadPool
1
(conc/counted-thread-factory "my-async-dispatch-%d" true)))
(alter-var-root #'clojure.core.async.impl.dispatch/executor
(constantly (delay (tp/thread-pool-executor my-executor))))
(async/go
(println
(Thread/currentThread))) ;=> #<Thread Thread[my-async-dispatch-1,5,main]>
Note: Core.async is still in alpha, so, hopefully, this will change in the future.注意: Core.async 仍处于 alpha 阶段,因此,希望将来会有所改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.