簡體   English   中英

在 Kotlin 協程中,同步是如何發生的?

[英]How does synchronization happens under the hood in Kotlin Coroutine?

我試圖了解協程如何訪問其他線程的數據。 看看下面的 kotlin 程序,我試圖了解主線程中的variableAccessCount AccessCount 可以從 Coroutine C1 和 Coroutine C2 訪問,但是根據我的理解,協程是在不同線程上運行的一段代碼,而在 Android 線程中不能直接接觸有機制可以做到這一點,例如處理程序,在協程中我們也有withContext()但特定於此示例,

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.coroutines.coroutineContext

var variableAccessCount = 0

fun main() {
    println("${Thread.currentThread()}")

    GlobalScope.launch {//Coroutine C1
        println("${Thread.currentThread()}")
        firstAccess() }

    GlobalScope.launch {//Coroutine C2
        println("${Thread.currentThread()}")
        secondAcess() }

    Thread.sleep(2000L)

    print("The variable is accessed $variableAccessCount number of times")
}

suspend fun firstAccess() {
    delay(500L)
    variableAccessCount++
}

suspend fun secondAcess() {
    delay(1000L)
    variableAccessCount++
}

有人能幫我理解同步是如何在變量var functionCalls = 0的幕后發生的嗎這個變量在主線程中聲明,可以從兩個掛起函數(completeMessage 和 improveMessage)訪問,它們在協程內運行但在不同的工作線程上.

程序O/P

Thread[main,5,main]
Thread[DefaultDispatcher-worker-3,5,main]
Thread[DefaultDispatcher-worker-2,5,main]
The variable is accessed 2 number of times
  • 使用AtomicInteger
val variableAccessCount = AtomicInteger(0)

suspend fun firstAccess() {
    delay(500L)
    variableAccessCount.incrementAndGet()
}

suspend fun secondAcess() {
    delay(1000L)
    variableAccessCount.incrementAndGet()
}
  • 線程限制細粒度
val counterContext = newSingleThreadContext("CounterContext")
var variableAccessCount = 0

suspend fun firstAccess() {
    delay(500L)
    withContext(counterContext) { variableAccessCount++ }
}

suspend fun secondAcess() {
    delay(1000L)
    withContext(counterContext) { variableAccessCount++ }
}
  • 互斥
val mutex = Mutex()
var variableAccessCount = 0

suspend fun firstAccess() {
    delay(500L)
    mutex.withLock  { variableAccessCount++ }
}

suspend fun secondAcess() {
    delay(1000L)
    mutex.withLock  { variableAccessCount++ }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM