Paul Martin
04/30/2020, 7:17 PMfun main() = runBlocking {
launch {
println("block 1: start")
delay(2000)
println("block 1: end")
}
launch {
println("block 2: start")
delay(1000)
println("block 2: end")
}
Unit
}
as expected, the output is:
block 1: start
block 2: start
block 2: end
block 1: end
so the two launch blocks are running concurrently.
next i try and replace the delay calls with some functions of my own:
fun functionThatTakesALongTime() {
for (j in 1..5) {
for (i in 1..1_000_000_000) {
i * i * i
}
}
}
fun functionThatTakesAShortTime() {
1 + 1
}
fun main() = runBlocking {
launch {
println("block 1: start")
functionThatTakesALongTime()
println("block 1: end")
}
launch {
println("block 2: start")
functionThatTakesAShortTime()
println("block 2: end")
}
Unit
}
this time the output is this:
block 1: start
block 1: end
block 2: start
block 2: end
in other words it ran the whole of the first launch block before starting on the second one. want i want is for them to run concurrently as in the first example.
i guess there's something fundamental that i'm missing! what is it about delay which enables the launch blocks to run concurrently?
thanks!octylFractal
04/30/2020, 7:18 PMdelay suspends while it waits, which allows the other launch block to run on the same single thread that is availableoctylFractal
04/30/2020, 7:19 PMPaul Martin
04/30/2020, 7:30 PMPaul Martin
04/30/2020, 8:10 PMPaul Martin
04/30/2020, 8:11 PMdelay in them can be running in parallel, but they're actually running concurrently in a single threadoctylFractal
04/30/2020, 8:15 PMrunBlockingoctylFractal
04/30/2020, 8:16 PMoctylFractal
04/30/2020, 8:17 PMuli
05/01/2020, 12:07 PMuli
05/01/2020, 12:08 PMsvenjacobs
05/04/2020, 3:13 PMrunBlocking should imho only be used in tests... when you replace runBlocking with with(GlobalScope) your code should run in parallel as expected. Note that the usage of GlobalScope is okay for your little test application but usually there are more granular scopes that should be used.uli
05/06/2020, 10:45 PMsvenjacobs
05/10/2020, 5:57 PMasync and awaitsvenjacobs
05/10/2020, 6:00 PMJob returned by launch with joinuli
05/10/2020, 10:03 PMsvenjacobs
05/13/2020, 7:31 AMlaunch inside runBlocking do not run concurrently? 🤔