Fredrik Rødland
03/20/2021, 4:37 PMpackage samples
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicLong
fun main() {
val c = AtomicLong()
for (i in 1..1_000_000L)
GlobalScope.launch {
c.addAndGet(i)
}
println(c.get())
}
PS! if this is better suited as question in #getting-started please tell me and I’ll move it there.Zach Klippenstein (he/him) [MOD]
03/20/2021, 4:59 PMZach Klippenstein (he/him) [MOD]
03/20/2021, 4:59 PMFredrik Rødland
03/20/2021, 4:59 PMGlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>)
- which gives the behaviourFredrik Rødland
03/20/2021, 5:00 PMFredrik Rødland
03/21/2021, 12:50 PMZach Klippenstein (he/him) [MOD]
03/21/2021, 2:29 PMDispatchers.Default
and <http://Dispatchers.IO|Dispatchers.IO>
give the same behavior? I’m surprised tooFredrik Rødland
03/21/2021, 3:41 PMFredrik Rødland
03/21/2021, 3:44 PMFredrik Rødland
03/21/2021, 3:44 PMfun main() {
listOf(Dispatchers.Default, <http://Dispatchers.IO|Dispatchers.IO>).forEach {
println("time used: with $it: " + measureTimeMillis { test1(it) })
}
}
private fun test1(dispatcher: CoroutineDispatcher) {
val c = AtomicLong()
for (i in 1..1_000_000L)
GlobalScope.launch(dispatcher) {
c.addAndGet(i)
}
println(c.get())
}
=>
500000500000
time used: with Dispatchers.Default: 2753
500000500000
time used: with <http://Dispatchers.IO|Dispatchers.IO>: 6783