What are use cases for coroutines?

One use case is a web server that has multiple simultaneous connections, with a requirement to schedule reading and writing in parallel with all of them.

This can be implemented using coroutines. Each connection is a coroutine that reads/writes some amount of data, then yields control to the scheduler. The scheduler passes to the next coroutine (which does the same thing), cycling through all the connections.


Use case: coroutines are often used in game programming to time-slice computations.

To maintain a consistent frame rate in a game, e.g., 60 fps, you have about 16.6ms to execute code in each frame. That includes physics simulation, input processing, drawing/painting.

Lets say your method is executed in every frame. If your method takes a long time and ends up spanning multiple frames, you are going to stagger the rest of the computation in the game loop which results in the user seeing "jank" (a sudden drop in frame rate).

Coroutines make it possible to time slice the computation so that it runs a little bit in each frame.

For that to happen, coroutines allow the method to "yield" the computation back to the "caller" (in this case the game loop) so that the next time the method is called it resumes from where it left off.