Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'thread'
QUEUE_SIZE = 2
POOL_SIZE = 5
queue = SizedQueue.new(QUEUE_SIZE)
producers = POOL_SIZE.times.map do
Thread.new do
item = rand(10)
queue.enq(item)
puts "--> Enqueue #{item}"
end
end
consumers = POOL_SIZE.times.map do
Thread.new do
begin
while item = queue.deq(true)
puts "--> Dequeue #{item}"
end
rescue ThreadError
end
end
end
producers.map(&:join)
consumers.map(&:join)
# --> Enqueue 6
# --> Enqueue 9
# --> Dequeue 6
# --> Dequeue 9
# --> Enqueue 0
# --> Enqueue 6
# --> Dequeue 0
# --> Dequeue 6
# --> Enqueue 6
# --> Dequeue 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment