This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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