Concurrency Quiz
Test your understanding of Ruby concurrency concepts including threads, fibers, ractors, async patterns, and best practices.
1 Thread Safety and Race Conditions
class Counter
def initialize
@count = 0
end
def increment
temp = @count
sleep(0.001) # Simulate some processing
@count = temp + 1
end
def value
@count
end
end
counter = Counter.new
threads = 10.times.map do
Thread.new { 100.times { counter.increment } }
end
threads.each(&:join)
puts counter.value
What will this code likely output, and why?
2 Global VM Lock (GVL) Understanding
Which scenario would benefit MOST from using multiple threads in Ruby, despite the Global VM Lock?
3 Fibers vs Threads
def process_with_threads
results = []
threads = 3.times.map do |i|
Thread.new do
sleep(1)
"Thread #{i} done"
end
end
threads.each { |t| results << t.value }
results
end
def process_with_fibers
results = []
fibers = 3.times.map do |i|
Fiber.new do
sleep(1)
"Fiber #{i} done"
end
end
fibers.each { |f| results << f.resume }
results
end
What's the key difference in execution between these two approaches?
4 Ractor Constraints
data = {
numbers: [1, 2, 3],
message: "hello",
flag: true
}
worker = Ractor.new do
received_data = Ractor.receive
# Process the data...
end
worker.send(data)
What will happen when this code runs?
5 Concurrent-Ruby Promises
require 'concurrent-ruby'
promise1 = Concurrent::Promise.execute { sleep(1); "First" }
promise2 = Concurrent::Promise.execute { sleep(2); raise "Error!" }
promise3 = Concurrent::Promise.execute { sleep(0.5); "Third" }
result = Concurrent::Promise.zip(promise1, promise2, promise3)
puts result.value
What will happen when this code executes?
6 Async Gem Event Loop
Which operation would BLOCK the event loop in the Async gem and should be avoided?
7 Producer-Consumer Pattern
In a producer-consumer pattern, what is the main advantage of using a bounded queue (SizedQueue) instead of an unbounded Queue?
8 Atomic Operations
require 'concurrent-ruby'
counter = Concurrent::AtomicFixnum.new(0)
10.times.map do
Thread.new do
100.times do
current = counter.value
counter.compare_and_set(current, current + 1)
end
end
end.each(&:join)
puts counter.value
What will this code likely output?
9 Concurrency Best Practices
Which of the following is considered a best practice for concurrent Ruby programming?
10 Choosing the Right Concurrency Model
You're building a web scraper that needs to download content from 10,000 URLs. Which concurrency approach would be most appropriate?