On 07/27/12 21:22, Stuart wrote:
> On Friday, 27 July 2012 at 19:17:10 UTC, H. S. Teoh wrote:
>>
>> Nevertheless, D has gotten to the point where it's powerful enough that most 
>> feature requests can be implemented in a
>> library rather than as a language extension.
> 
> How could Yield be implemented as a library feature? Something like:
> 
>    return ITERATOR(
>       { ...setup code ... },
>       { ...loop body code... })
> 
> ?
> 
> I don't see how that would work.

The threading "yield" and the iterator "yield" are actually strongly related. 
By yielding a coroutine, you can effectively suspend a routine
and resume it later. Let me give you an example:

int delegate() genEvenNumbers() {
  // not actual api
  return startCoroutineIterator!int((void delegate(int) yield) {
    for (int i = 0; true; i++) if (i % 2 == 0) yield(i);
  });
}

// long form of the above function, so you can see how you gain iterator-style 
behavior via coroutines
int delegate() genEvenNumbers() {
  int* resultp = new int;
  void cofun(void delegate(int) yield) {
    for (int i = 0; true; i++) if (i % 2 == 0) yield(i);
  }
  // still not actual api
  auto coroutine = new Coroutine(1024*1024 /* stack size */);
  // set the 'main function' of the coroutine
  coroutine.fun = {
    // yield, when called, will cause the coroutine to suspend and run() to 
return
    cofun((int i) { *resultp = i; coroutine.yield(); });
  };
  // run the coroutine up to the next yield, then return yielded value
  return { coroutine.run(); return *resultp; };
}

You can fully implement Coroutine as a library, provided you're somewhat 
confident with x86 assembly and stack frame layouts.

Reply via email to