【问题标题】:Clojure core.async, any way to control number of threads in that (go...) thread pool?Clojure core.async,有什么方法可以控制该(go ...)线程池中的线程数?
【发布时间】:2013-09-13 06:02:20
【问题描述】:

默认情况下 (go..) 将使用twice the number of cores + 42 线程作为线程池。有什么方法可以通过设置环境变量或其他方式来设置线程数或代码可以使用的 CPU 数?

在 linux 机器上,我可以使用 taskset 设置 CPU 数量,例如 taskset -c 0,1 my_Java_or_Clojure_program,虽然taskset 似乎对(-> (java.lang.Runtime/getRuntime) .availableProcessors) 返回的数字无效。

【问题讨论】:

标签: multithreading clojure cpu-usage core.async


【解决方案1】:

当前接受的答案在 this commit 之前有效,所以基本上现在你有两种情况:

  • 如果您只想更改池中的最大线程数,请将数字作为 Java 属性 clojure.core.async.pool-size 传递(默认为 8)

  • 如果你想替换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)))
    

【讨论】:

    【解决方案2】:

    在当前 Clojure 版本的 core.async 中,线程池执行器位于 clojure.core.async.impl.dispatch 命名空间中。您可以更改 executor 变量并提供自定义线程池 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]>
    

    注意:Core.async 仍处于 alpha 阶段,因此希望将来会有所改变。

    【讨论】:

    • 我只想补充一点,当且仅当您在 core.async 调用创建函数之前更改 var 时才有效,所以这应该在您的程序的早期就需要
    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 2011-10-14
    • 2016-08-28
    • 2019-12-29
    • 2014-08-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多