Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you implement Coroutines in C++

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?

like image 994
Mike Elkins Avatar asked Sep 23 '08 15:09

Mike Elkins


People also ask

How are coroutines implemented?

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.

What are coroutines in C?

Coroutines are general control structures where flow control is cooperatively passed between two different routines without returning.

What do you mean by coroutines?

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.

Why cactus stack is used in coroutine?

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.


1 Answers

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.

like image 159
Ted Avatar answered Sep 25 '22 03:09

Ted