Implementation of Coroutine in Cpp

Version 1.0

If you are interested in how to write a python generator or a lua coroutine in C++, this code does the job for you

I am not going to explain how it works, but if you are interested in the implementation, feel free to read the source code…

I wrote some posts on the story of how I came up with this idea, but all of them are in Chinese. Read them here: Cartesian Product and Cartesian Product 2

This small implememation is very easy to use, so I wrote an usage manual in the souece code to show how to use it.

If you still have any questions on how to use it, or some new ideas on this topic, feel free to send me an email.

Hope you enjoy my code, and have fun to play with it! :)

Version 1: Source Code with Manual and Examples

Version 2.0

After I read the source code generated by the preprocessor, it was a big surprise for me, the switch statement is much more powerful than I thought…

Then I did some research online, and found someone had the same idea decades ago! Read this: Coroutines in C. So, I simplify my code and update it to version 2.

In version 2, it’s free to use all control flow statements in cpp, and we don’t declare the YIELD statement before using it.

Example:

PRG_BEG
for(i = 0; i < 10; ++i) {
  output = i;
  YIELD();
}
PRG_END

The ONLY thing must be kept in mind is that all local variables are better to become the members of the generator class! The OTHER thing is that NEVER have two YIELD() in the same line!

Version 2: Source Code with Examples