Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bf4/4b8e68c513a765bbe562 to your computer and use it in GitHub Desktop.
Save bf4/4b8e68c513a765bbe562 to your computer and use it in GitHub Desktop.
#
# Apparently this has been in Ruby since 1.9.3... who knew?
# Also check out sized queue class
#
require 'thread'
#
# Create a new thread that blocks on queue pop
# Create an "exit" channel to send "stop" message when total of 100 is reached
#
def totaller
queue, hammer_time = Queue.new, Queue.new
Thread.new do
total = 0
while (value = queue.pop)
puts "totaller: Adding value #{value} to #{total}"
total += value
hammer_time << "stop" if total > 100
end
end
[queue, hammer_time]
end
queue, hammer_time = totaller
#
# New thread that queues up messages for threads
#
Thread.new do
loop do
val = rand(20)
puts "queueing #{val}"
queue << val
end
end
# Block until 'stop' message has been sent.
hammer_time.pop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment