Bird
0
0

You want to run three tasks in parallel using fork and wait for all to finish. Which code correctly achieves this?

hard📝 Application Q8 of 15
Ruby - Concurrent Programming
You want to run three tasks in parallel using fork and wait for all to finish. Which code correctly achieves this?
A3.times { fork { puts 'Task' }; Process.wait }
Bpids = 3.times.map { fork { puts 'Task' } }; Process.waitall(pids)
C3.times.map { fork { puts 'Task' } }; Process.wait
Dpids = 3.times.map { fork { puts 'Task' } }; pids.each { |pid| Process.wait(pid) }
Step-by-Step Solution
Solution:
  1. Step 1: Fork three child processes and collect PIDs

    Using 3.times.map { fork { ... } } stores child PIDs in an array.
  2. Step 2: Wait for each child process individually

    Iterate over PIDs and call Process.wait(pid) to wait for each child.
  3. Final Answer:

    pids = 3.times.map { fork { puts 'Task' } }; pids.each { |pid| Process.wait(pid) } -> Option D
  4. Quick Check:

    Fork multiple and wait each PID = pids = 3.times.map { fork { puts 'Task' } }; pids.each { |pid| Process.wait(pid) } [OK]
Quick Trick: Collect PIDs, then wait each to sync parallel tasks [OK]
Common Mistakes:
  • Calling Process.wait inside loop without PID (serializes forks)
  • Using Process.wait after multiple forks (waits only one child)
  • Passing pids to Process.waitall (arity error)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes