Created
March 12, 2013 21:30
-
-
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?
This file contains hidden or 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
#!/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