【发布时间】:2020-03-13 01:33:46
【问题描述】:
我决定深入研究 Kotlin 协程。我有一些关于能见度的问题。我知道在没有ContinuationInterceptor 的情况下,同一协程的不同部分可能由不同的线程执行。
如何保证在暂停后,新线程对协程内部状态有正确的可见性?
例如:
suspend fun doPost(customRatings : Map<String, Int>) : Int {...}
fun postRatings_1() {
GlobalScope.launch {
val mutableMap : MutableMap<String, Int> = mutableMapOf()
mutableMap["Apple"] = 1
mutableMap["Banana"] = 2
// ...
val postId = doPost(mutableMap)
// How am I guaranteed to see the two entries here ?
println("posted ${mutableMap} with id ${postId}")
}
}
同样当一个新的协程启动时
fun postRatings_2() {
val mutableMap : MutableMap<String, Int> = mutableMapOf()
mutableMap["Apple"] = 1
mutableMap["Banana"] = 2
GlobalScope.launch {
// How am I guaranteed to see the two entries here ?
val postId = doPost(mutableMap)
//...
}
在这两种情况下,两个(现有)线程之间共享一些可变状态。
我正在寻找“Happens-before”规则,以保证可变状态对两个线程正确可见。
【问题讨论】:
标签: multithreading kotlin concurrency kotlin-coroutines