Process Forking for Parallelism in Ruby
📖 Scenario: You have a list of tasks that take some time to complete. To finish faster, you want to run some tasks at the same time using Ruby's process forking.
🎯 Goal: Build a Ruby program that uses fork to run two tasks in parallel and then waits for both to finish before printing a message.
📋 What You'll Learn
Create an array called
tasks with two strings: 'Task 1' and 'Task 2'.Create an empty array called
pids to store process IDs.Use a
for loop with variable task to iterate over tasks.Inside the loop, use
fork to create a child process that prints "Starting: #{task}", sleeps for 2 seconds, then prints "Finished: #{task}".Store each child process ID in
pids.After the loop, use
Process.wait(pid) for each pid in pids to wait for all child processes to finish.Finally, print
"All tasks completed.".💡 Why This Matters
🌍 Real World
Running multiple tasks at the same time can save time in programs that do many independent jobs, like downloading files or processing data.
💼 Career
Understanding process forking is useful for backend developers and system programmers who need to optimize performance by running tasks in parallel.
Progress0 / 4 steps