Coroutines in Kotlin
Coroutines != Thread
The biggest misconception about coroutines. Let’s try to understand this word better.
Co + routines = Cooperative functions working together.
What are cooperative functions?
funA(){
1...
2...
pass control to funB()
5...
6...
pass control to funB()
}funB(){
3...
4...
pass control to funA()
7...
8...
exit
}
Thus order of execution: 1->2->3->4->5->6->7->8->exit
Both funA and funB are not restricting each other from execution. This means they are cooperative in nature.
A thread is managed by an Operating System, where we need context switching in order to change between multiple threads. But, a coroutine is managed by a user, and switching between functions is very easy here(as shown above).
we can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate.
Multiple coroutines can run on a single thread without blocking each other. This helps in bringing out maximum output from the thread.
We can say, a coroutine is more like a framework that manages concurrency by working on top of the actual threading system and taking help of the co-operative nature of functions.
Coroutines are basically of two types:
- stackless coroutines
- stackful coroutines
Kotlin implements stackless coroutines — these coroutines does not have their own stack. it uses the same runtime-stack as the host side.
Stackful coroutine needs to allocate a certain amount of memory to accomodate its runtime-stack.
Hope this will help you.