0
0
Rubyprogramming~3 mins

Why Fiber for cooperative concurrency in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could juggle tasks like a skilled performer, never dropping a ball?

The Scenario

Imagine you have several tasks to do, like cooking, cleaning, and answering messages, but you can only do one at a time. You try to switch between them manually, stopping one task and starting another whenever you want.

The Problem

This manual switching is slow and confusing. You might forget where you left off, or tasks might block each other, making everything take longer and causing mistakes.

The Solution

Fibers let you pause and resume tasks smoothly, like having a helper who remembers exactly where you stopped. This way, you can switch between tasks without losing progress, making your program faster and easier to manage.

Before vs After
Before
def task1
  puts 'Start task1'
  sleep(1)
  puts 'End task1'
end

def task2
  puts 'Start task2'
  sleep(1)
  puts 'End task2'
end

task1
 task2
After
fiber1 = Fiber.new do
  puts 'Start task1'
  Fiber.yield
  puts 'End task1'
end

fiber2 = Fiber.new do
  puts 'Start task2'
  Fiber.yield
  puts 'End task2'
end

fiber1.resume
fiber2.resume
fiber1.resume
fiber2.resume
What It Enables

Fibers enable smooth multitasking by letting your program pause and resume tasks exactly when you want.

Real Life Example

Think of a video game where the character can perform actions like running, jumping, and shooting without freezing the game; fibers help manage these actions smoothly behind the scenes.

Key Takeaways

Manual task switching is slow and error-prone.

Fibers let you pause and resume tasks easily.

This makes programs faster and simpler to manage.