Jan*_*ski 3 multithreading jvm kotlin kotlinx.coroutines
我正在试验Kotlin 协程并有以下代码:
fun main(args: Array<String>) = runBlocking {
val cores = Runtime.getRuntime().availableProcessors()
println("number of cores: $cores")
val jobs = List(10) {
async(CommonPool) {
delay(100)
println("async #$it on thread ${Thread.currentThread().name}")
}
}
jobs.forEach { it.join() }
}
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
number of cores: 4
async number:0 on thread ForkJoinPool.commonPool-worker-2
async number:2 on thread ForkJoinPool.commonPool-worker-3
async number:3 on thread ForkJoinPool.commonPool-worker-3
async number:4 on thread ForkJoinPool.commonPool-worker-3
async number:5 on thread ForkJoinPool.commonPool-worker-3
async number:1 on thread ForkJoinPool.commonPool-worker-1
async number:7 on thread ForkJoinPool.commonPool-worker-3
async number:6 on thread ForkJoinPool.commonPool-worker-2
async number:9 on thread ForkJoinPool.commonPool-worker-3
async number:8 on thread ForkJoinPool.commonPool-worker-1
Run Code Online (Sandbox Code Playgroud)
据罗马Elizarov的回答相关问题,另一个协同程序:
“启动只是创建了新的协程,而 CommonPool 将协程分派到 ForkJoinPool.commonPool(),它确实使用了多个线程,因此在这个例子中在多个 CPU 上执行。”
根据 Java 8文档:
“对于需要单独或自定义池的应用程序,可以使用给定的目标并行级别构建 ForkJoinPool;默认情况下,等于可用处理器的数量。”
为什么只使用了 3 个工作线程?即使我将异步任务的数量增加到 1000+,也有相同的 3 个工作线程。
我的配置:Mac/High Sierra 带双核 cpu(带超线程,因此有 4 个可见内核)、Kotlin 1.2、kotlinx-coroutines-core:0.19.3 和 JVM 1.8
如果您查看 的实现CommonPool,您会注意到它正在处理java.util.concurrent.ForkJoinPool或具有以下大小的线程池:
(Runtime.getRuntime().availableProcessors() - 1).coerceAtLeast(1)
Run Code Online (Sandbox Code Playgroud)
使用4可用的处理器,这将导致3您看到 3 个工作线程的原因。
所述ForkJoinPool-size可以如下(将是相同的)来确定:
ForkJoinPool.commonPool().parallelism
Run Code Online (Sandbox Code Playgroud)
如果您使用协程版本 >= 1.0,请参阅此答案
| 归档时间: |
|
| 查看次数: |
3050 次 |
| 最近记录: |