0
0
Rubyprogramming~30 mins

Process forking for parallelism in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the tasks array
Create an array called tasks with these exact strings: 'Task 1' and 'Task 2'.
Ruby
Need a hint?

Use square brackets [] to create an array with two strings.

2
Create the pids array
Create an empty array called pids to store process IDs.
Ruby
Need a hint?

Use [] to create an empty array.

3
Fork processes for each task
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.
Ruby
Need a hint?

Use fork do ... end to create a child process. Use pids << pid to add the process ID to the array.

4
Wait for all child processes and print completion
After the loop, use Process.wait(pid) for each pid in pids to wait for all child processes to finish. Then print "All tasks completed.".
Ruby
Need a hint?

Use Process.wait(pid) to wait for each child process. Then print the final message.