0
0
Rubyprogramming~5 mins

Process forking for parallelism in Ruby

Choose your learning style9 modes available
Introduction

Process forking lets a program do many things at the same time by creating copies of itself. This helps finish tasks faster.

When you want to run multiple tasks at once to save time.
When a program needs to handle many users or requests simultaneously.
When you want to split a big job into smaller parts that run together.
When you want to keep the main program running while doing background work.
When you want to use multiple CPU cores to speed up processing.
Syntax
Ruby
pid = fork do
  # code to run in the child process
end

Process.wait(pid) # wait for the child process to finish

The fork method creates a new child process.

The block after fork runs only in the child process.

Examples
This example shows a child process printing a message, then the parent waits and prints its message.
Ruby
pid = fork do
  puts "Child process running"
end
Process.wait(pid)
puts "Parent process finished"
Child process does nothing and exits immediately. Parent waits and prints after child ends.
Ruby
pid = fork do
  # Child does nothing
end
Process.wait(pid)
puts "Child done"
Child sleeps for 2 seconds while parent continues immediately, then waits for child to finish.
Ruby
pid = fork do
  puts "Child start"
  sleep 2
  puts "Child end"
end
puts "Parent continues"
Process.wait(pid)
Sample Program

This program shows the parent process creating a child process. The child prints messages and sleeps for 1 second to simulate work. The parent waits for the child to finish before exiting.

Ruby
puts "Parent process ID: #{Process.pid}"
pid = fork do
  puts "Child process ID: #{Process.pid}"
  puts "Child is working..."
  sleep 1
  puts "Child finished work"
end
puts "Parent is waiting for child to finish"
Process.wait(pid)
puts "Child process has finished. Parent exiting."
OutputSuccess
Important Notes

Time complexity depends on the tasks inside the child process, but forking itself is fast.

Space complexity increases because the child process is a copy of the parent.

Common mistake: forgetting to wait for child processes, which can cause zombie processes.

Use forking when tasks are independent and can run at the same time. Use threads if tasks share memory and need communication.

Summary

Forking creates a new process to run code in parallel.

The child process runs the block given to fork.

The parent can wait for the child to finish using Process.wait.