Junior — Middle
What value will the counter variable take after launching 100 coroutines, each of which will increase its value by 1 a thousand times?
sobes.tech AI
Answer from AI
If 100 coroutines simultaneously increment the same counter variable 1000 times without synchronization, the final value will most likely be less than the expected 100,000 (100 * 1000) due to race conditions.
This is because increment operations are not atomic: read, increment, and write can be interrupted by other coroutines.
To get the correct result, synchronization mechanisms such as Mutex from kotlinx.coroutines should be used:
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
var counter = 0
val mutex = Mutex()
fun main() = runBlocking {
val jobs = List(100) {
launch {
repeat(1000) {
mutex.withLock {
counter++
}
}
}
}
jobs.forEach { it.join() }
println(counter) // Will output 100000
}
Without such protection, the final value will be unpredictable.