Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/native/src/MultithreadedDispatchers.kt (Kotlin)

Code before:
        while (true) {
            val state = tasksAndWorkersCounter.getAndUpdate {
                if (it.isClosed() && !it.hasTasks()) return@runBlocking
                it - 2
            }
            if (state.hasTasks()) {
                // we promised to process a task, and there are some
                tasksQueue.receive().run()
            } else {
                try {
                    suspendCancellableCoroutine {
                        availableWorkers.trySend(it)
                    }.run()
                } catch (e: CancellationException) {
                    /** we are cancelled from [close] and thus will never get back to this branch of code,
                    but there may still be pending work, so we can't just exit here. */
                }
            }
        }
    }

    private fun obtainWorker(): CancellableContinuation<Runnable> {
        // spin loop until a worker that promised to be here actually arrives.
        while (true) {
            val result = availableWorkers.tryReceive()
            return result.getOrNull() ?: continue
        }
    }

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        val state = tasksAndWorkersCounter.getAndUpdate {
            if (it.isClosed())
                throw IllegalStateException("Dispatcher $name was closed, attempted to schedule: $block")
            it + 2
        }
        if (state.hasWorkers()) {
            // there are workers that have nothing to do, let's grab one of them
            obtainWorker().resume(block)
        } else {
            workerPool.allocate()
            // no workers are available, we must queue the task
            tasksQueue.trySend(block)
        }
    }

    override fun close() {
        tasksAndWorkersCounter.getAndUpdate { if (it.isClosed()) it else it or 1L }
        val workers = workerPool.close() // no new workers will be created
        while (true) {
            // check if there are workers that await tasks in their personal channels, we need to wake them up
            val state = tasksAndWorkersCounter.getAndUpdate {

Review comment (bug):
I'm a bit reluctant about having potentially infinite spinloops in case of un unforeseen bug or failure.
It would be nice to replace it with (non-existing) `receiveBlocking` which could've been a direct counterpart of `sendBlocking`

Code after:
        while (true) {
            val state = tasksAndWorkersCounter.getAndUpdate {
                if (it.isClosed() && !it.hasTasks()) return@runBlocking
                it - 2
            }
            if (state.hasTasks()) {
                // we promised to process a task, and there are some
                tasksQueue.receive().run()
            } else {
                try {
                    suspendCancellableCoroutine {
                        val result = availableWorkers.trySend(it)
                        checkChannelResult(result)
                    }.run()
                } catch (e: CancellationException) {
                    /** we are cancelled from [close] and thus will never get back to this branch of code,
                    but there may still be pending work, so we can't just exit here. */
                }
            }
        }
    }

    // a worker that promised to be here and should actually arrive, so we wait for it in a blocking manner.
    private fun obtainWorker(): CancellableContinuation<Runnable> =
        availableWorkers.tryReceive().getOrNull() ?: runBlocking { availableWorkers.receive() }

    override fun dispatch(context: CoroutineContext, block: Runnable) {
        val state = tasksAndWorkersCounter.getAndUpdate {
            if (it.isClosed())
                throw IllegalStateException("Dispatcher $name was closed, attempted to schedule: $block")
            it + 2
        }
        if (state.hasWorkers()) {
            // there are workers that have nothing to do, let's grab one of them
            obtainWorker().resume(block)
        } else {
            workerPool.allocate()
            // no workers are available, we must queue the task
            val result = tasksQueue.trySend(block)
            checkChannelResult(result)
        }
    }

    override fun close() {
        tasksAndWorkersCounter.getAndUpdate { if (it.isClosed()) it else it or 1L }
        val workers = workerPool.close() // no new workers will be created
        while (true) {
            // check if there are workers that await tasks in their personal channels, we need to wake them up
            val state = tasksAndWorkersCounter.getAndUpdate {
                if (it.hasWorkers()) it + 2 else it
            }