I am trying to understand how does coroutines access other thread's data. Just have a look on below kotlin program in which I tried to understand the variableAccessCount
in main thread can be accessed from Coroutine C1 & Coroutine C2 however as per my understanding coroutines are piece of code which runs on different threads and in Android threads can't be touched directly there is mechanism to do that such as Handler, in coroutine also we do have withContext() but specific to this example,
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++
}
Would somebody help me to understand How does synchronization happens under the hood for variable var functionCalls = 0 This variable is declared in Main thread and can be accessed from both suspend functions (completeMessage & improveMessage), which are running inside coroutine but on different worker thread.
Program 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