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

Code before:
     * (number of tasks - number of workers) * 2 + (1 if closed)
     */
    private val tasksAndWorkersCounter = atomic(0L)

    private inline fun Long.isClosed() = this and 1L == 1L
    private inline fun Long.hasTasks() = this >= 2
    private inline fun Long.hasWorkers() = this < 0

    private fun workerRunLoop() = runBlocking {
        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)

Review comment (bug):
But we immediately can go on a second iteration, start executing line 101 and fail with another CE, never giving this thread change to invoke `getAndUpdate`, potentially leading to hanging `close`?

Code after:
     * (number of tasks - number of workers) * 2 + (1 if closed)
     */
    private val tasksAndWorkersCounter = atomic(0L)

    private inline fun Long.isClosed() = this and 1L == 1L
    private inline fun Long.hasTasks() = this >= 2
    private inline fun Long.hasWorkers() = this < 0

    private fun workerRunLoop() = runBlocking {
        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)
        }
    }