I can currently think of two ways of implementing a coroutine:
- Whenever a coroutine is started, instead of storing local variables on stack, get a piece of memory from heap and use it to store local variables. This way, local variables are not destroyed, and any called function can return to this function later in time. But in this case, any called function which is not a coroutine has to run on main call stack. I don't know if this could cause any problem. Can someone confirm it!
- Whenever a coroutine is started, allocate a bigger amount of memory than required to that coroutine. This would act like some kind of custom call stack for that coroutine. In this case, all the sub-functions called by this would be stored together with this coroutine. But this implementation may require too much of redundant memory.
I think these two are popularly known as stackless and stackful coroutines.
What are other theoretically possible ways of implementing a coroutine? What are advantages and disadvantages of them? Which languages use which implementations?