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:
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.Call
Fiber.yield
periodically inside your fiber to let other fibers run. Theyield
function will return control to the function that called the fiber.Pass messages to worker threads to perform long computations.
The
main
function is responsible for scheduling the fibers. It should call thecall
function on the fibers when it is ready to...