[OT] Stackless fibers/coroutines

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Sun Sep 25 23:42:51 PDT 2016


On 2016-09-25 20:16, Nick Sabalausky wrote:

> Resumable Function:
> -------------------
> This sounds like a vague general term to me. I would think it casually
> refers to any function that can be suspended/resumed: A Fiber-based
> coroutine, a stackless coroutine, or whatever else may or may not exist.

I think this is the term used in now in C++. It looks like it will have 
a lower level API for suspending and resuming functions. Then it's 
possible to build on top of this different concurrency constructs as 
libraries, like coroutines, stackless threads, goroutines, async/await 
and so on.

> I don't see why not, but there would be one notable drawback: You could
> only have one instance existing at a time (per thread).

But how does it work in languages which don't pass in the state 
explicitly, like with "yield" in C#?

Or async/await? I guess one doesn't call the function multiple times in 
the same way instead it's done automatically under the hood, passing in 
the state which might be stored in the "Task" that is returned?

> I'd have to look it up and refresh my memory. I just remember D has more
> restrictions regarding jumping to labels than C has. Something like:
>
> ------------------
> State myCoroutine(State s) {
>     yield "hello";
>
>     if(foo) {
>         yield " world";
>     }
>
>     yield "!";
> }
> ------------------
>
> A Protothreads-like preprocessing approach that used switch/case would
> turn that into:
>
> ------------------
> State myCoroutine(State s) {
> switch(s.jumpLabel){
>     case 0:
>     // Start converted code: //////////////
>
>     //yield "hello"; -> return+case:
>     return State(1, "hello");
>     case 1:
>
>     if(int foo = getFoo()) {
>         //yield " world"; ->
>         return State(2, " world"); return+case:
>         case 2:
>     }
>
>     //yield "!"; -> return+case:
>     return State(3, "!");
>     case 3:
>
>     // End converted code //////////////
>     break;
> }
> }
> ------------------
>
> That "if" really messed things up. AIUI, I don't think D will allow
> things like that.

The above code compiles, after removing the extra "return+case:".

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list