Is something like this thread-safe? (Not real code, just the concept)
Copy code
withContext(Dispatchers.Default) {
var x = false
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
x = true
})
println(x)
}
I understand that the three lines (
var x = false
,
x = true
,
println(x)
) will run "one at a time" but are all the right things done with the memory model to guarantee that the write will be seen by the println, without needing to use atomics or the like?
g
gildor
08/27/2019, 5:23 AM
yes, there is happens-before relations, so it’s safe, it would be more clear if you check resulting byte-code, where each suspend point represented by state machine states and correctness of this state machine guaranteed by kotlin compiler
gildor
08/28/2019, 1:24 AM
It consequent out of semantics of suspend functions, but not sure that there is some formal spec for this