Ruby不执行所有线程的代码

时间:2014-02-06 00:43:03

标签: ruby multithreading

我正在学习如何在Ruby中使用线程,但我发现了一个非常奇怪的问题。这就是代码:

require 'active_record'
require 'rss'
require 'open-uri'
require 'thread'
require_relative 'model/post'
require_relative 'model/source'

queue = Queue.new
producer = []

ActiveRecord::Base.establish_connection(
    adapter: "postgresql",
    host: "localhost",
    database: "trendy",
    username: "postgres",
    password: "postgres"
)

sources = Source.all
puts "Active Record has loaded: #{sources.length} feeds"
sources.each do |source|
  producer << Thread.new do
    puts "Feed: #{source.url}"
  end
end

producer.join

puts "Number of threads created #{producer.length}"

这就是输出:

Active Record has loaded: 5 feeds
Feed: http://alt1040.com/feed
Feed: http://appleweblog.com/feedNumber of threads created 5

Process finished with exit code 0

如果再次运行,您会发现该程序不会打印两个Feed,我的意思是,程序打印的Feed数量是随机的。

我看不出问题......

1 个答案:

答案 0 :(得分:2)

你不是在等他们完成。你需要调用producer.each(&amp;:join)。 producer.join在数组上调用join