Skip to content

Instantly share code, notes, and snippets.

@terabyte
Created March 12, 2013 21:30
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 terabyte/5147248 to your computer and use it in GitHub Desktop.
Save terabyte/5147248 to your computer and use it in GitHub Desktop.
If you comment out the Thread.pass in this example, under Ruby 1.9.2 at least, the producer runs forever and the consumers never run (or at least don't run until the producer is completely done). WTF?
#!/usr/bin/env ruby
require 'thread'
work = Queue.new
producer = Thread.new do
(1..10000).each do |i|
work << i
sleep 0.1
puts "P: #{Thread.current.inspect}"
Thread.pass
end
end
shutdown = false
consumer = []
2.times do |i|
consumer << Thread.new do
while shutdown == false
item = work.pop
puts "Processing #{item}"
Thread.pass
puts "C: #{Thread.current.inspect}"
end
end
end
puts "M: #{Thread.current.inspect}"
Thread.pass
producer.join
while !work.empty?
sleep 0.1
end
shutdown = true
consumer.each {|x| x.kill}
consumer.each {|x| x.join}
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment