Skip to content

Commit 87244f9

Browse files
authored
Short-circuit limitedParallelism for K/N multi-worker dispatcher (#4118)
1 parent dfbd4a8 commit 87244f9

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

kotlinx-coroutines-core/native/src/MultithreadedDispatchers.kt

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ internal class WorkerDispatcher(name: String) : CloseableCoroutineDispatcher(),
7777

7878
private class MultiWorkerDispatcher(
7979
private val name: String,
80-
workersCount: Int
80+
private val workersCount: Int
8181
) : CloseableCoroutineDispatcher() {
8282
private val tasksQueue = Channel<Runnable>(Channel.UNLIMITED)
8383
private val availableWorkers = Channel<CancellableContinuation<Runnable>>(Channel.UNLIMITED)
@@ -140,6 +140,15 @@ private class MultiWorkerDispatcher(
140140
}
141141
}
142142

143+
@ExperimentalCoroutinesApi
144+
override fun limitedParallelism(parallelism: Int, name: String?): CoroutineDispatcher {
145+
parallelism.checkParallelism()
146+
if (parallelism >= workersCount) {
147+
return namedOrThis(name)
148+
}
149+
return super.limitedParallelism(parallelism, name)
150+
}
151+
143152
override fun close() {
144153
tasksAndWorkersCounter.getAndUpdate { if (it.isClosed()) it else it or 1L }
145154
val workers = workerPool.close() // no new workers will be created

0 commit comments

Comments
 (0)