https://kotlinlang.org logo
#coroutines
Title
# coroutines
k

kevin.cianfarini

03/20/2020, 3:20 PM
Simple question... will corotuines launched in a dispatcher that's backed by a thread pool implicitly be parallelized? Eg.
Copy code
suspend fun foo() = withContext(Dispatchers.Default) {
    for (1..100) {
        async { ... }
    }
}
Will that be bound to a single thread or will is try to spread the workload?
s

streetsofboston

03/20/2020, 3:27 PM
Yup, this is the way to parallelize it (
Default
is backed by a thread pool of more than one thread), but i don’t think the exact number of parallel threads is guaranteed.
k

kevin.cianfarini

03/20/2020, 3:27 PM
cool. Thanks 🙂
z

Zach Klippenstein (he/him) [MOD]

03/20/2020, 3:33 PM
This is documented in the kdoc on `Dispatchers.Default`:
Copy code
It is backed by a shared pool of threads on JVM. By default, the maximal level of parallelism used by this dispatcher is equal to the number of CPU cores, but is at least two. Level of parallelism X guarantees that no more than X tasks can be executed in this dispatcher in parallel.
On JS, there are no threads, and this dispatcher is just backed by the JS event loop, which is not parallelized.
k

kevin.cianfarini

03/20/2020, 3:39 PM
sure, that makes sense
On native I assume they spin up their own threadpool?
l

louiscad

03/20/2020, 4:06 PM
On native, there's only one thread for now because of different concurrency model
👍 3
k

kevin.cianfarini

03/20/2020, 4:20 PM
That's changing though, right?
l

louiscad

03/20/2020, 4:44 PM
Not yet as far as I know.
k

kevin.cianfarini

03/20/2020, 5:22 PM
I understand that's a very rough draft, but I thought it was making progress
l

louiscad

03/20/2020, 5:59 PM
Quoting from that very same page:
A Default dispatcher on Kotlin/Native contains a single background thread
k

kevin.cianfarini

03/20/2020, 6:00 PM
gotcha. I figured that was going to be temporary but maybe not?
l

louiscad

03/20/2020, 6:01 PM
It's as written after what I quoted on that very same page.
k

kevin.cianfarini

03/20/2020, 6:03 PM
ooof lol. Thanks for the insight though!
2 Views