Bird
0
0

What is wrong with this Ruby code that tries to use concurrency?

medium📝 Debug Q14 of 15
Ruby - Concurrent Programming
What is wrong with this Ruby code that tries to use concurrency?
threads = []
i = 0
5.times do
  threads << Thread.new do
    puts i
  end
  i += 1
end
threads.each(&:join)
AThe code will cause a syntax error.
BThe variable i is shared and may cause unexpected output.
Cthreads.each(&:join) should be threads.join.
DThread.new is not the correct way to create threads.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable capture in threads

    The block uses variable i from the loop, which may change before thread runs, causing unexpected output.
  2. Step 2: Identify concurrency issue

    Each thread may print the same or wrong i value because i is shared and changes quickly.
  3. Final Answer:

    The variable i is shared and may cause unexpected output. -> Option B
  4. Quick Check:

    Loop variable shared in threads causes bugs [OK]
Quick Trick: Loop variables shared in threads cause unexpected values [OK]
Common Mistakes:
  • Thinking Thread.new is wrong syntax
  • Confusing threads.each(&:join) with threads.join
  • Assuming syntax error without checking code

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes