4 ms·
It’s a little more complicated than that, and Kotlin co-routine docs aren’t great at describing the internals of the coroutines infrastructure. Coroutines by d
by avianlyric 3y ago
It’s a little more complicated than that, and Kotlin co-routine docs aren’t great at describing the internals of the coroutines infrastructure.
Coroutines by default are launched without an dispatcher, and simply create a single threaded event loop that schedules a single co-routine at a time to use the thread that created the coroutine scope. In this world the is no multithreading and coroutines can’t be moved between system threads, and no thread pools or equivalent are created.
However in most uses of coroutines (especially on Android), you’ll have a framework that already created a coroutine scope (using something like runBlocking) and provided the default dispatcher as the coroutine scopes dispatcher, which is then automatically inherited by any child coroutines or coroutines scope.
Personally I wished they had called Dispatchers.Default something else, it’s a confusing and slightly misleading name, given Dispatchers aren’t a hard requirement to use coroutines.
But I agree the big think to take away from Kotlin coroutines is structured concurrency, and the ergonomics to provides to manage concurrent operations in simple clean manner that avoids nasty resource leakages.
For everything else in coroutines, it’s pretty easy to reconfigure the coroutine runtime to use also most any underlying threading model, including ThreadPools, Singleton Threads, virtual threads, and my favourite, no additional threads whatsoever.
The above means that measuring coroutine startup and creation time and comparing it to threads kinda misses the point of using coroutines in the first place. And it’s possible to make coroutine creation cheaper or more expensive, depending on how exactly you’ve setup your coroutine scope, and which dispatchers (if any) you’re using.
- mmis1000 3y agoI think the most powerful thing of coroutine is you can switch to other os thread without lost the scope and context as long as you implement the dispatcher of such os thread (it's likely it will be the os ui thread, because tons of system have such limit). You will usually rely on observer or publish/subscribe model to do such things before coroutine exists. Because you can't magically change the current thread. It's not how it works. And unlike virtual thread. The underlying infrastructure is exposed directly to end user. So you can write your own dispatcher or continuation with ease as long as you know what are you doing. Make it more useful as a low level building block of a high level framework/library.