Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin Nativeにおけるfrozen状態と並行処理について

Kotlin Nativeにおけるfrozen状態と並行処理について

Flutter × Kotlin Multiplatform by CyberAgent #2の登壇資料です。

Sato Shun

March 02, 2021
Tweet

More Decks by Sato Shun

Other Decks in Programming

Transcript

  1. frozenঢ়ଶ? • ͦͷΠϯελϯε͕immutableͰ͋Δ͜ͱΛอূ͢Δ /** * Freezes object subgraph reachable from

    this object. Frozen objects can be freely * shared between threads/workers. * * @throws FreezingException if freezing is not possible * @return the object itself * @see ensureNeverFrozen */ public fun <T> T.freeze(): T
  2. frozenঢ়ଶ? • ͦͷΠϯελϯε͕immutableͰ͋Δ͜ͱΛอূ͢Δ • freezeͨ͠ΠϯελϯεΛมߋ͠Α͏ͱ͢ΔͱɺΫϥογϡ͢Δ • ଞͷεϨουͱ҆શʹڞ༗͢Δ͜ͱ͕ग़དྷΔ /** * Checks

    if given object is null or frozen or permanent (i.e. instantiated at compile-time). * * @return true if given object is null or frozen or permanent */ public val Any ?. isFrozen
  3. val sample = Sample(3) sample.i + + sample.freeze() sample.i +

    + Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException
  4. object DefaultGlobalState { private var i = 5 fun countUp()

    { i ++ } } Uncaught Kotlin exception: kotlin.native.concurrent.InvalidMutabilityException
  5. val worker = Worker.start() worker.execute(TransferMode.SAFE, { … }) { …

    } public fun <T1, T2> execute( mode: TransferMode, producer: () -> T1, @VolatileLambda job: (T1) - > T2 ): Future<T2>
  6. data class Sample(var i: Int) val sample = Sample(1) worker.execute(TransferMode.SAFE,

    { sample }) { println(it) } Uncaught Kotlin exception: kotlin.IllegalStateException: Illegal transfer state
  7. data class Sample(var i: Int) val sample = Sample(1) val

    sample2 = Sample(2) worker.execute(TransferMode.SAFE, { sample.freeze() }) { println(it) }
  8. data class Sample(var i: Int) val sample = Sample(1) val

    sample2 = Sample(2) fun background(block: () -> Unit) { worker.execute(TransferMode.SAFE, { block.freeze() }) { it() } }
  9. data class Sample(var i: Int) val sample = Sample(1) val

    sample2 = Sample(2) background { println(sample) println(sample2) } fun background(block: () -> Unit) { worker.execute(TransferMode.SAFE, { block.freeze() }) { it() } }
  10. data class Sample(var i: Int) val sample = Sample(1) val

    sample2 = Sample(2) background { println(sample) println(sample2) } fun background(block: () -> Unit) { worker.execute(TransferMode.SAFE, { block.freeze() }) { it() } } sampleɺsample2ຊମΛfreeze͍ͯ͠ͳ͍ εϨου͕มΘΔ৔߹͸ɺfreeze͠ͳ͍ͱ͍͚ͳ͍ͷͰ͸?
  11. data class Sample(var i: Int) val sample = Sample(1) val

    sample2 = Sample(2) background { println(sample) println(sample2) } fun background(block: () -> Unit) { worker.execute(TransferMode.SAFE, { block.freeze() }) { it() } } sampleɺsample2ຊମΛfreeze͍ͯ͠ͳ͍ εϨου͕มΘΔ৔߹͸ɺfreeze͠ͳ͍ͱ͍͚ͳ͍ͷͰ͸? ϥϜμຊମΛfreeze͢Δͱɺ ͦͷϥϜμ͕ࢀর͍ͯ͠Δม਺΋࿈࠯తʹfreeze͞ΕΔ