Reputation: 3349
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.
Upvotes: 12
Views: 2185
Reputation: 200148
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.
Upvotes: 10