All Downloads are FREE. Search and download functionalities are using the official Maven repository.

darwinMain.io.islandtime.internal.Concurrency.kt Maven / Gradle / Ivy

The newest version!
package io.islandtime.internal

import kotlinx.cinterop.StableRef
import kotlin.native.concurrent.TransferMode
import kotlin.native.concurrent.Worker
import kotlin.native.concurrent.ensureNeverFrozen
import kotlin.native.concurrent.freeze

internal class WorkerConfined(
    private val worker: Worker,
    private val value: ConfinedValueRef
) {
    inline fun  use(crossinline block: (T) -> R): R {
        return runOn(worker) { block(value.get()) }
    }
}

internal inline class ConfinedValueRef(private val value: StableRef) {
    fun get() = value.get()

    companion object {
        fun  create(value: T): ConfinedValueRef {
            return ConfinedValueRef(StableRef.create(value.apply { ensureNeverFrozen() }))
        }
    }
}

internal inline fun  Worker.confine(crossinline block: () -> T): WorkerConfined {
    return WorkerConfined(
        this,
        runOn(this) { ConfinedValueRef.create(block()) }
    )
}

private inline fun  runOn(worker: Worker, crossinline block: () -> T): T {
    return if (worker == Worker.current) {
        block()
    } else {
        worker.executeImmediately { block() }
    }
}

private fun  Worker.executeImmediately(block: () -> T): T {
    return execute(
        TransferMode.SAFE,
        { block.freeze() },
        { runCatching { it() }.freeze() }
    ).result.getOrThrow()
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy