Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Created December 30, 2015 11:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifyouseewendy/a8fc663ae575843f9e8f to your computer and use it in GitHub Desktop.
Save ifyouseewendy/a8fc663ae575843f9e8f to your computer and use it in GitHub Desktop.
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