Test your understanding of Ruby concurrency concepts including threads, fibers, ractors, async patterns, and best practices.
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?
Which scenario would benefit MOST from using multiple threads in Ruby, despite the Global VM Lock?
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?
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?
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?
Which operation would BLOCK the event loop in the Async gem and should be avoided?
In a producer-consumer pattern, what is the main advantage of using a bounded queue (SizedQueue) instead of an unbounded Queue?
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?
Which of the following is considered a best practice for concurrent Ruby programming?
You're building a web scraper that needs to download content from 10,000 URLs. Which concurrency approach would be most appropriate?
Watch and learn quiz: concurrency