Consider the following Ruby code using threads. What will be printed?
count = 0 threads = [] 5.times do threads << Thread.new do 1000.times { count += 1 } end end threads.each(&:join) puts count
Think about how Ruby's GIL affects thread execution and shared variable updates.
Because of the GIL, threads do not run Ruby code truly in parallel. However, the increment operation is not atomic, so race conditions occur. This causes the final count to be less than 5000.
Choose the statement that correctly describes how Ruby's GIL affects CPU-bound threads.
Consider how the GIL serializes execution of Ruby code.
The GIL ensures only one thread executes Ruby code at a time, so CPU-bound threads cannot run in parallel on multiple cores.
Examine the code below. Why does the final printed value vary each run?
total = 0 threads = [] 10.times do threads << Thread.new do 100.times { total += 1 } end end threads.each(&:join) puts total
Think about what happens when multiple threads update the same variable without locks.
The increments on 'total' are not atomic, so race conditions cause inconsistent final values despite the GIL.
Choose the code that safely increments a shared counter variable using threads in Ruby.
Look for proper use of Mutex to avoid race conditions.
Option D uses a Mutex and synchronizes increments, preventing race conditions. Option D lacks synchronization. Option D uses mutex without defining it. Option D does not join threads before printing.
Which approach allows Ruby programs to perform true parallel execution despite the GIL?
Think about how to bypass the GIL's single-thread execution limitation.
Ruby's GIL limits threads to one core at a time. Using multiple processes allows true parallelism because each process has its own interpreter and memory space.