Implement async/await using Fiber
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 19 16:42:03 PDT 2016
On 05/19/2016 12:57 PM, Yuxuan Shui wrote:
> I find this difficult because I can't passing data via
> Fiber.yield/Fiber.call pair. e.g. I want something like:
>
> void fiberFunc() {
> //Add some file descriptor to main loop
> string y = Fiber.yield();
> writeln(y);
> }
>
> auto f = new Fiber(&fiberFunc);
> f.call();
> mainloop {
> if (fd_readable)
> f.call(fd.rawRead());
> }
>
> I can probably using a derived fiber class and pass the result via class
> members, but that seems clumsy and not very general. Any ideas?
>
You can use a delegate that takes a ref parameter:
import std.stdio;
import core.thread;
void fiberFunc(ref string y) {
y = "produced_by_fiberFunc";
Fiber.yield();
}
void main() {
string data;
auto f = new Fiber(() => fiberFunc(data));
f.call();
writefln("Writing in main: %s", data);
}
Prints:
Writing in main: produced_by_fiberFunc
Also see std.concurrency.Generator. Both methods appear here:
http://ddili.org/ders/d.en/fibers.html
Ali
More information about the Digitalmars-d-learn
mailing list