|
4 | 4 |
|
5 | 5 | package kotlinx.coroutines
|
6 | 6 |
|
| 7 | +import kotlinx.atomicfu.* |
7 | 8 | import kotlinx.coroutines.channels.*
|
8 | 9 | import kotlinx.coroutines.internal.*
|
9 | 10 | import kotlin.coroutines.*
|
@@ -73,43 +74,91 @@ private class MultiWorkerDispatcher(
|
73 | 74 | workersCount: Int
|
74 | 75 | ) : CloseableCoroutineDispatcher() {
|
75 | 76 | private val tasksQueue = Channel<Runnable>(Channel.UNLIMITED)
|
| 77 | + private val availableWorkers = Channel<CancellableContinuation<Runnable>>(Channel.UNLIMITED) |
76 | 78 | private val workerPool = OnDemandAllocatingPool(workersCount) {
|
77 | 79 | Worker.start(name = "$name-$it").apply {
|
78 | 80 | executeAfter { workerRunLoop() }
|
79 | 81 | }
|
80 | 82 | }
|
81 | 83 |
|
| 84 | + /** |
| 85 | + * (number of tasks - number of workers) * 2 + (1 if closed) |
| 86 | + */ |
| 87 | + private val tasksAndWorkersCounter = atomic(0L) |
| 88 | + |
| 89 | + private inline fun Long.isClosed() = this and 1L == 1L |
| 90 | + private inline fun Long.hasTasks() = this >= 2 |
| 91 | + private inline fun Long.hasWorkers() = this < 0 |
| 92 | + |
82 | 93 | private fun workerRunLoop() = runBlocking {
|
83 |
| - // NB: we leverage tail-call optimization in this loop, do not replace it with |
84 |
| - // .receive() without proper evaluation |
85 |
| - for (task in tasksQueue) { |
86 |
| - /** |
87 |
| - * Any unhandled exception here will pass through worker's boundary and will be properly reported. |
88 |
| - */ |
89 |
| - task.run() |
| 94 | + while (true) { |
| 95 | + val state = tasksAndWorkersCounter.getAndUpdate { |
| 96 | + if (it.isClosed() && !it.hasTasks()) return@runBlocking |
| 97 | + it - 2 |
| 98 | + } |
| 99 | + if (state.hasTasks()) { |
| 100 | + // we promised to process a task, and there are some |
| 101 | + tasksQueue.receive().run() |
| 102 | + } else { |
| 103 | + try { |
| 104 | + suspendCancellableCoroutine { |
| 105 | + val result = availableWorkers.trySend(it) |
| 106 | + checkChannelResult(result) |
| 107 | + }.run() |
| 108 | + } catch (e: CancellationException) { |
| 109 | + /** we are cancelled from [close] and thus will never get back to this branch of code, |
| 110 | + but there may still be pending work, so we can't just exit here. */ |
| 111 | + } |
| 112 | + } |
90 | 113 | }
|
91 | 114 | }
|
92 | 115 |
|
| 116 | + // a worker that promised to be here and should actually arrive, so we wait for it in a blocking manner. |
| 117 | + private fun obtainWorker(): CancellableContinuation<Runnable> = |
| 118 | + availableWorkers.tryReceive().getOrNull() ?: runBlocking { availableWorkers.receive() } |
| 119 | + |
93 | 120 | override fun dispatch(context: CoroutineContext, block: Runnable) {
|
94 |
| - fun throwClosed(block: Runnable) { |
95 |
| - throw IllegalStateException("Dispatcher $name was closed, attempted to schedule: $block") |
| 121 | + val state = tasksAndWorkersCounter.getAndUpdate { |
| 122 | + if (it.isClosed()) |
| 123 | + throw IllegalStateException("Dispatcher $name was closed, attempted to schedule: $block") |
| 124 | + it + 2 |
96 | 125 | }
|
97 |
| - |
98 |
| - if (!workerPool.allocate()) throwClosed(block) // Do not even try to send to avoid race |
99 |
| - |
100 |
| - tasksQueue.trySend(block).onClosed { |
101 |
| - throwClosed(block) |
| 126 | + if (state.hasWorkers()) { |
| 127 | + // there are workers that have nothing to do, let's grab one of them |
| 128 | + obtainWorker().resume(block) |
| 129 | + } else { |
| 130 | + workerPool.allocate() |
| 131 | + // no workers are available, we must queue the task |
| 132 | + val result = tasksQueue.trySend(block) |
| 133 | + checkChannelResult(result) |
102 | 134 | }
|
103 | 135 | }
|
104 | 136 |
|
105 | 137 | override fun close() {
|
106 |
| - val workers = workerPool.close() |
107 |
| - tasksQueue.close() |
| 138 | + tasksAndWorkersCounter.getAndUpdate { if (it.isClosed()) it else it or 1L } |
| 139 | + val workers = workerPool.close() // no new workers will be created |
| 140 | + while (true) { |
| 141 | + // check if there are workers that await tasks in their personal channels, we need to wake them up |
| 142 | + val state = tasksAndWorkersCounter.getAndUpdate { |
| 143 | + if (it.hasWorkers()) it + 2 else it |
| 144 | + } |
| 145 | + if (!state.hasWorkers()) |
| 146 | + break |
| 147 | + obtainWorker().cancel() |
| 148 | + } |
108 | 149 | /*
|
109 | 150 | * Here we cannot avoid waiting on `.result`, otherwise it will lead
|
110 | 151 | * to a native memory leak, including a pthread handle.
|
111 | 152 | */
|
112 | 153 | val requests = workers.map { it.requestTermination() }
|
113 | 154 | requests.map { it.result }
|
114 | 155 | }
|
| 156 | + |
| 157 | + private fun checkChannelResult(result: ChannelResult<*>) { |
| 158 | + if (!result.isSuccess) |
| 159 | + throw IllegalStateException( |
| 160 | + "Internal invariants of $this were violated, please file a bug to kotlinx.coroutines", |
| 161 | + result.exceptionOrNull() |
| 162 | + ) |
| 163 | + } |
115 | 164 | }
|
0 commit comments