Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Coroutines don't really have anything to do with threads. They are just a way for you to model suspending and resuming functions.

If you have every tried to implement a complicated iterator you will find that you model a for loop in your head but that the iteration of the loop is controlled from outside using the ++ operator. The ++ operator allows the iterator loop to go one more time round. Normally you have to manage this with state stored in some object. With coroutines you can actually write a loop and co_yield from the middle of the loop to implement the ++ operator.



Co-routines can be a great structured-programming tool for implementing state machines. A good article which explains this idea explicitly: https://eli.thegreenplace.net/2009/08/29/co-routines-as-an-a...

That said, overhead always needs to be considered; the overhead cost of using a CPP co-routine would be considerable for implementing a state machine that transitions rapidly.


This is actually really convenient.

In our code we have an abstraction that wraps a set using a variant. Instead of implementing an iterator/begin/end based on which data the variant holds, we have an iter() method that unwraps the variant and loops through and co_yields. Since you can consume a generator in a for-each loop, you use it the exact same way (except calling iter).

In our case it doesn't save that much complexity, but it's definitely some. I could imagine more complicated cases where it is even more convenient.


Everyone who ever programmed a bit in Python knows that. Generators simplify your code and remove unnecessary boilerplate.

However, async/await is real nice as well.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: