fibers and ranges: what's wrong here?

zeljkog via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Dec 13 04:01:40 PST 2014


import std.stdio, core.thread;

struct Tree{
     int val;
     Tree[] tree;
}

struct TreeRange{
   Tree curtree;
   bool empty;
   Fiber worker;

   this(Tree t){
     worker = new Fiber(&fiberFunc);
     curtree = t;
     popFront();
   }
   void fiberFunc(){
     Tree t = curtree;
     Fiber.yield();
     foreach(child; t.tree){
       curtree = child;
       fiberFunc();
     }
   }
   int front(){ return curtree.val; };
   void popFront() {
     worker.call();
     empty = worker.state == Fiber.State.TERM;
   }
}

void main() {
   auto tt = Tree(5, [Tree(7,[Tree(11), Tree(4)]), Tree(10)]);
   auto tr1 = TreeRange(tt);
   foreach(v; tr1){
     writef("%2d, ", v);
   }
   writeln();
   for(auto r = TreeRange(tt); !r.empty; r.popFront())
     writef("%2d, ", r.front);
   writeln();
}

output:
  5,  5,  5,  5,  5,
  5,  7, 11,  4, 10,

Is it supposed to work?


More information about the Digitalmars-d-learn mailing list