0
0
Rubyprogramming~20 mins

Fiber for cooperative concurrency in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Fiber for cooperative concurrency
📖 Scenario: You are building a simple program that uses Ruby Fiber to switch between two tasks cooperatively. This simulates how two workers take turns doing their jobs without interrupting each other.
🎯 Goal: Create two Fiber objects that print messages in turns, showing how cooperative concurrency works with Fiber.yield and Fiber.resume.
📋 What You'll Learn
Create two Fiber objects named fiber1 and fiber2.
Each fiber should print a message and then yield control.
Use a loop to resume each fiber alternately two times.
Print the messages exactly as specified.
💡 Why This Matters
🌍 Real World
Fibers let programs switch between tasks without waiting for one to finish, useful in games, network servers, or UI where tasks share time smoothly.
💼 Career
Understanding fibers helps in writing efficient Ruby programs that handle multiple tasks cooperatively, improving responsiveness and resource use.
Progress0 / 4 steps
1
Create two Fiber objects
Create two Fiber objects called fiber1 and fiber2. fiber1 should print "Fiber 1: Step 1" and then yield. fiber2 should print "Fiber 2: Step 1" and then yield.
Ruby
Need a hint?

Use Fiber.new do ... end to create fibers. Inside each, print the message and call Fiber.yield to pause.

2
Add second steps inside fibers
Inside fiber1, after the first yield, print "Fiber 1: Step 2". Inside fiber2, after the first yield, print "Fiber 2: Step 2". Add these lines after the first Fiber.yield in each fiber.
Ruby
Need a hint?

After Fiber.yield, add a puts line for the second step message inside each fiber.

3
Create a loop to resume fibers alternately
Create a 2.times do loop. Inside the loop, resume fiber1 and then resume fiber2 to switch between them.
Ruby
Need a hint?

Use 2.times do to repeat two times. Inside, call fiber1.resume then fiber2.resume.

4
Run the program and print the output
Run the program as is. The output should show the fibers printing their steps alternately. No extra code needed, just run the existing code.
Ruby
Need a hint?

Just run the program. You will see the fibers print their messages in turns twice.