Forked from pricees/ruby_queues_are_essentially_go_channels.rb
Last active
August 29, 2015 14:09
-
-
Save bf4/4b8e68c513a765bbe562 to your computer and use it in GitHub Desktop.
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
# | |
# 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