Marko Mitic
08/01/2019, 9:17 PMsynchonized
block. Here's the test, results in thread
import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
class Test {
var i = 0
suspend fun countWithThreadSwitching(){
repeat(10) {
i++
delay(1) //yield() didn't make coroutine resume on another thread
}
println(i)
}
}
fun main() = runBlocking {
coroutineScope{
repeat(100) {
launch(Dispatchers.Default) {
Test().countWithThreadSwitching()
}
}
}
}
Marko Mitic
08/01/2019, 9:18 PMDominaezzz
08/01/2019, 9:48 PMMarko Mitic
08/01/2019, 9:51 PMMarko Mitic
08/01/2019, 9:52 PMDominaezzz
08/01/2019, 10:00 PMDico
08/02/2019, 1:25 AMJag
08/02/2019, 2:33 AM@Test
fun main() = runBlocking {
repeat(100) {
val t = Test()
coroutineScope {
launch(Dispatchers.Default) {
t.countWithThreadSwitching()
}
}
println(t.i)
}
}
Marko Mitic
08/02/2019, 8:46 AMMarko Mitic
08/02/2019, 8:47 AMMarko Mitic
08/02/2019, 8:49 AMyield
to release current thread and another thread from pool to pick up the coroutine for execution laterMarko Mitic
08/02/2019, 8:53 AMdelay(1)
instead of yield()
did the trickDico
08/02/2019, 8:59 AMDico
08/02/2019, 9:00 AMMarko Mitic
08/02/2019, 9:07 AMMarko Mitic
08/02/2019, 9:09 AMDominaezzz
08/02/2019, 9:41 AMMarko Mitic
08/02/2019, 9:43 AMMarko Mitic
08/02/2019, 9:44 AMvolatile
Dominaezzz
08/02/2019, 9:45 AMDominaezzz
08/02/2019, 9:45 AMvolatile
just tells the compiler to take it easy with the optimizations.Dominaezzz
08/02/2019, 9:48 AMMarko Mitic
08/02/2019, 9:48 AMMarko Mitic
08/02/2019, 9:49 AMMarko Mitic
08/02/2019, 9:51 AMsynchronized
block, caches are invalidated and before leaving it, caches are flushed (ok, that part is CPU automatic)Marko Mitic
08/02/2019, 9:51 AMDominaezzz
08/02/2019, 9:53 AMDominaezzz
08/02/2019, 9:54 AM