Learn Fibers in Ruby

Tram Ho

Ruby on Rails comes with an Active Job framework for declaring and running them on some backend queues. Jobs can range from simple things like cleaning schedules, paying monthly fees, sending mail, etc.

In this article, you’ll learn how it works, leveraging Fiber performance in Ruby for the project.

What are Fibers?

Fibers are workers, they run code and track their own process or in other words fibers are a simultaneous mechanism.

Fibers are similar to Threads but differ in that they allow more management on fibers than threads.

  • What will we think it allows for more management? The operating system decides when to run threads and when to stop them.
  • The above does not apply to fibers! We need to tell a fiber exactly when to run and when to stop.

Fibers vs Threads

Threads allow the sensor to work in the background.

  • Fiber does not do this.

When a fiber is running it becomes the main program until it stops. Take a look at the usage example below: Create a fiber with Fiber.new and a block.

After that, to run fiber, we need to use resume method.

It will print 1 and it returns the management to the main program.

How to stop a fiber?

With the method Fiber.yield differs from the yield keyword for blocks .

After starting the fiber it will print 1 with resume then stop. If you continue calling the resume again it will continue correctly from where it left off and print 2 .

Note: Running resume again will return the error FiberError: dead fiber called because there is no more code to run.

This is a feature of using fiber.

Calling Fiber.yield in a fiber is like pressing the pause button, allowing you to stop in the middle of the loop or any code written in a fiber block.

Fiber and Loops: Endless series

We can use nút pause effect to create an infinite sequence.

Things needed to create endless series

  • Fibers
  • Loop
  • Counter

Example: Factorial number

We can use the fiber as many times as we want with the resume method to get the next number in the sequence.

For example:

Fibers and IO: Asynchronous operation

Fibers are faster and more efficient than threads for things to wait like network connections.

Why?

Because fiber gives little context for swtich context. A context switch is when the CPU changes from the current task to another task.

This is a bit of a price, but it adds a lot! Start using fibers:

Remember: It’s not a miracle it’s worth testing and seeing how fiber can help us

Conclude

This is the end of the lesson to learn how Fibers work in Ruby! A fiber allows to create a code unit that can be stopped and continued as desired

Refer

Share the news now

Source : Viblo