Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using fibers


Fibers are similar to threads, but are more lightweight and cooperative rather than pre-emptive. That is, a fiber must explicitly yield to pass control to another fiber, either by calling the yield function directly or through a function that yields for you (such as an I/O function). On the other hand, threads will be scheduled automatically by the operating system and may be interrupted at any time.

How to do it…

Let us execute the following steps:

  1. Create a fiber with new Fiber. You do not have to create a special storage location for your state because fibers automatically save and restore their own stacks, so regular local variables will work.

  2. Call Fiber.yield periodically inside your fiber to let other fibers run. The yield function will return control to the function that called the fiber.

  3. Pass messages to worker threads to perform long computations.

  4. The main function is responsible for scheduling the fibers. It should call the call function on the fibers when it is ready to...