I doubt it can be done portably, but are there any solutions out there? I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP. Destructors and exception safety seem tricky but solvable.
Has it been done? Is it impossible?
A coroutine internally uses a Continuation class to capture the contexts for its execution. Then the dynamic aspect is modeled as a Job class. The use of async usually creates a Deferred job, which is a subclass of the Job class. The CoroutineContext type is required for a coroutine to execute.
Coroutines are general control structures where flow control is cooperatively passed between two different routines without returning.
A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.
To implement sharing, the run-time system must employ a so-called cactus stack. Each branch off the stack contains the frames of a separate coroutine. The static chain of the coroutine, however, extends down into the remainder of the cactus, through any lexically surrounding blocks.
Yes it can be done without a problem. All you need is a little assembly code to move the call stack to a newly allocated stack on the heap.
I would look at the boost::coroutine library.
The one thing that you should watch out for is a stack overflow. On most operating systems overflowing the stack will cause a segfault because virtual memory page is not mapped. However if you allocate the stack on the heap you don't get any guarantee. Just keep that in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With