https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

David Glasser

08/27/2019, 4:14 AM
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
It consequent out of semantics of suspend functions, but not sure that there is some formal spec for this
s

streetsofboston

08/28/2019, 2:52 AM
I read it somewhere....but the only place I can find right now where sequentiality/happens-before is mentioned, is here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/composing-suspending-functions.md
a

Allan Wang

08/28/2019, 2:54 AM
Is the question here moreso on volatility rather than sequence? I do wonder this too, though examples seem to show that it's fine
g

gildor

08/28/2019, 3:28 AM
volatility is just way to force happened-before relation, here it provided by coroutines compiler and runtime
3 Views