On Sunday, 12 June 2016 at 02:43:40 UTC, Patric Dexheimer wrote:
I learned about Fibers on D, and now I´m starting to read about it (Threads/Fibers/Coroutines) etc. But when I try to make something usefull with it I just fail to see the real advantage over a normal structured programming without it.

Can someone show some code with usefull/unique/advantageous use of fibers?
Thanks in advance!

Fibers since they use the same thread as what calls them, it doesn't seem like it would help much. However if there is a delay for something for some reason (IO, or putting a delay in the current logic for a little while) then (to my understanding) Fibers kicks in and lets you keep going.

A big reason you would want Fibers is not to lose the time slot your code has for working, not because it makes the program slower, but if the OS switches to another process, when it returns you have cold data (not cached).

So, assuming you have stuff to work on and you want to open a file too, you might do it like this.

work(someargs); //work could be moved after the reading of content too...
  string content = readFile("Some file.txt");

This will process work and then open the file. However while the file is opening it may be a while before the file fully opens, or can be read the physical IO (spinning disks waiting on the OS, other delays) may end up dropping your current time slot.

A fiber on the other hand you would do it this way: (API is probably wrong, so don't rely on this example to actually compile)

  Fiber fiber = new Fiber();
  Fiber.run(work, someargs);
  string content = readFile("Some file.txt");

Now when the blocking IO happens during opening or reading, the Fiber takes over and does some work in the background. If you recently worked on any data that remains hot (cached) and you get better performance as long as it's hot.

To note I am still watching the recent DConf 2016 which sorta covers this, which is much better than my reply :P

Reply via email to