What are use cases for coroutines?

Mnementh picture Mnementh · Nov 20, 2008 · Viewed 13.4k times · Source

The concept of a coroutine sounds very interesting, but I don't know, if it makes sense in a real productive environment? What are use cases for coroutines, where the coroutine implementation is more elegant, simpler or more efficient than other methods?

Answer

Ali Afshar picture Ali Afshar · Nov 20, 2008

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.