I was going through the concept of co-routines and it's usage and implementation in kotlin.
I googled and read few answers as in how it is different from threads in terms of architecture and performance.
Very well explained here,
Difference between a "coroutine" and a "thread"?
Fair enough, co-routines are great, no memory overhead, great performance, no dead-locks, race-conditions and etc. and easy to use.
Now, here are few things, I am confused about and would like more clarity on the same -
Co-routines are great to use, but how it takes advantage of multiple cores for performance.
Coroutines can achieve preemptive scheduling and require lesser resources than threads. Threads mostly minimize the context switching time and provide concurrency in the process. Threads have efficient communication and are more economical in the creation and context switching of threads.
A coroutine can provide a very high level of concurrency with very small overhead. Multiple threads can also provide parallelism but there is blocking and context switching. Coroutine suspends the thread and does not block it so that it can switch to another work .
Coroutines provide sophisticated tools to enable concurrency but don't give us parallelism for free. In some situations, it will be necessary to dispatch blocking code onto some worker threads to let the main program flow continue.
When the number of Thread and Coroutine is very small, Thread is faster. However, when the number becomes bigger, Coroutine is much faster.
Threads and coroutines are almost orthogonal features.
Coroutines are about your programming model and threads are about your execution model.
If you want to fetch a URL or perform a heavyweight computation in Android, you have to use async programming. You have the choice to do it the old-fashioned way, with callbacks, or with coroutines, which make those crutches disappear. You simply call a suspendable function and get the result as its return value.
Note that for the heavyweight computation you'll use extra threads with or without coroutines. For network ops you don't need extra threads, with or without coroutines.
A great analogy is that threads are to coroutines what CPU cores are to threads:
The OS assigns a thread to a CPU core until the thread suspends. Later on, the same thread can resume on another core.
The coroutine dispatcher assigns a coroutine to a thread until the coroutine suspends. Later on, the same coroutine can resume on another thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With