Yield from function?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 31 03:31:28 PST 2017


On 01/31/2017 03:00 AM, Profile Anaysis wrote:

 > Just curious, how can I use start() recursively?
[...]
 > Seems I can't create start with a parameter and non-void return type.

Options:

- The class can maintain state

- You can start the fiber with a delegate;

     int local;
     double state;
     () => foo(local, state)

Other than the entry point, there is no requirement in what you can do. 
The following code yields inside a recursive function:

import std.stdio, std.concurrency, core.thread;

class Search : Fiber
{
     int state;

     this(int state) {
         this.state = state;
         super(&start);
     }
     int res = 0;
     void start() {
         recursive(state);
     }

     void recursive(int s) {
         if (s == 0) {
             return;
         }
         res = s;
         Fiber.yield();
         recursive(s - 1);
     }
}

void main()
{
     auto search = new Search(42);

     foreach (i; 0 .. 5) {
         search.call();
         writeln(search.res);
     }
}

Ali



More information about the Digitalmars-d-learn mailing list