Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active December 16, 2015 11:49
Show Gist options
  • Save havenwood/5430600 to your computer and use it in GitHub Desktop.
Save havenwood/5430600 to your computer and use it in GitHub Desktop.
SizedQueue Basic Usage
require 'thread'
# Create a SizedQueue with a buffer capacity of just one.
queue = SizedQueue.new 1
# Add four symbols to the SizedQueue. (A SizedQueue is thread-safe just like a
# Queue.)
Thread.new { queue << :of }
Thread.new { queue << :earl }
Thread.new { queue << :and }
Thread.new { queue << :midge }
# With a SizedQueue capcity of one, three of the four are waiting enqueue
# (queued, waiting to get into the queue (inception two levels deep)) and the
# remaining one is in the queue buffer itself.
queue.max
#=> 1
queue.num_waiting
#=> 3
# If the SizedQueue capacity is increased dynamically, elements in the enqueue
# will scootch over into the queue buffer.
queue.max = 3
#=> 3
queue.num_waiting
#=> 1
# Likewise, if the SizedQueue is decremented by an element, one of the enqueue
# will hop into the queue buffer.
queue.shift
#=> :of
queue.num_waiting
#=> 0
# So now there is a SizedQueue with a fixed buffer capacity of three, which is
# full with nothing enqueue.
queue.shift
#=> :earl
queue.shift
#=> :and
queue.shift
#=> :midge
# Once the queue is empty, trying to decrement an element will block until an
# element is added to the queue.
queue.shift
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment