Hacker News new | ask | show | jobs
by Calavar 1042 days ago
What are some of the other use cases?
2 comments

Many coroutine uses are not asynchronous, but synchronous, they block when resumed and do not execute in parallel. This permits cooperative multitasking, versus preemptive (or preemptive with a bunch of locks to imitate cooperative which is, of course, a waste). Since they can, in principle, execute within the same thread (with C++'s implementation and some others you the programmer can send them off to other threads for execution, but that's an explicit choice) this can simplify concurrent system design and execution (in the concurrency is not parallelism sense). In the single threaded case, it's also faster than multithreaded asynchronous code since the context switching (modulo cache misses) is greatly reduced. Especially useful in the case where you want synchrony and not asynchrony.

They're also very useful if you've ever had to create a bare metal multitasking system. Much easier for state management than older style "while (true)" loops with a million state variables so functions can resume via a switch/case as pseudo-coroutines. (Well, easier if you don't have to implement the coroutine mechanism yourself.)

Generators come to my mind.