What are the differences between a \"coroutine\" and a \"thread\"?
About 7 years late, but the answers here are missing some context on co-routines vs threads. Why are coroutines receiving so much attention lately, and when would I use them compared to threads?
First of all if coroutines run concurrently (never in parallel), why would anyone prefer them over threads?
The answer is that coroutines can provide a very high level of concurrency with very little overhead. Generally in a threaded environment you have at most 30-50 threads before the amount of overhead wasted actually scheduling these threads (by the system scheduler) significantly cuts into the amount of time the threads actually do useful work.
Ok so with threads you can have parallelism, but not too much parallelism, isn't that still better than a co-routine running in a single thread? Well not necessarily. Remember a co-routine can still do concurrency without scheduler overhead - it simply manages the context-switching itself.
For example if you have a routine doing some work and it performs an operation you know will block for some time (i.e. a network request), with a co-routine you can immediately switch to another routine without the overhead of including the system scheduler in this decision - yes you the programmer must specify when co-routines can switch.
With a lot of routines doing very small bits of work and voluntarily switching between each other, you've reached a level of efficiency no scheduler could ever hope to achieve. You can now have thousands of coroutines working together as opposed to tens of threads.
Because your routines now switch between each other a pre-determined points you can now also avoid locking on shared data structures (because you would never tell your code to switch to another coroutine in the middle of a critical section)
Another benefit is the much lower memory usage. With the threaded-model, each thread needs to allocate its own stack, and so your memory usage grows linearly with the number of threads you have. With co-routines, the number of routines you have doesn't have a direct relationship with your memory usage.
And finally, co-routines are receiving a lot of attention because in some programming languages (such as Python) your threads cannot run in parallel anyway - they run concurrently just like coroutines, but without the low memory and free scheduling overhead.