Sachin Maharana
10/22/2020, 12:10 PMimport kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
import kotlinx.coroutines.delay
fun main() = runBlocking {
println("${Thread.activeCount()} threads active at the start")
val time = measureTimeMillis {
createCoroutines(10_000)
}
println("${Thread.activeCount()} threads active at the end")
println("Took $time ms")
}
suspend fun createCoroutines(amount: Int) {
val jobs = ArrayList<Job>()
for (i in 1..amount) {
jobs += launch {
delay(1000)
}
}
jobs.forEach {
it.join()
}
}
william
10/22/2020, 12:11 PMbezrukov
10/22/2020, 12:14 PMlaunch
, right?
launch
is a CoroutineScope's extension, so you need a scope to call it.
Here is an idiomatic way to write this:
fun main() = runBlocking {
println("${Thread.activeCount()} threads active at the start")
val time = measureTimeMillis {
createCoroutines(10_000)
}
println("${Thread.activeCount()} threads active at the end")
println("Took $time ms")
}
suspend fun createCoroutines(amount: Int) = coroutineScope {
for (i in 1..amount) {
launch {
delay(1000)
}
}
}
Sachin Maharana
10/22/2020, 12:14 PMe: /home/test/IdeaProjects/Coroutines/src/main/kotlin/main.kt: (29, 17): Unresolved reference: launch
Sachin Maharana
10/22/2020, 12:17 PMSachin Maharana
10/22/2020, 12:18 PMbezrukov
10/22/2020, 12:23 PMBut i assumed, if i am using runBLocking in main , doesn't that gives scope to the createCoroutine function.No, to have a CoroutineScope as a receiver type for
createCoroutines
you need explicitly write it:
fun CoroutineScope.createCoroutines(amount....
but it is not recommended way.
Without it, where the compiler should take a scope, if you call this function from outside of runBlocking
?
Also, is there a difference between runBlocking scope and coroutineScope?yes, runBlocking can be called from non-suspending fun, while coroutineScope can be only called from
suspend
fun.