Serginho
Serginho

Reputation: 7490

Ruby doesn't execute the code of all threads

I'm learning about how to use threads in Ruby but I've found with a very strange problem. That's the code:

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}"

And that's the output:

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

If you run again, you will find out that the program doesn't print two feeds, I mean, the number of feeds that the program prints is random.

I can't see the problem...

Upvotes: 0

Views: 58

Answers (1)

bridiver
bridiver

Reputation: 1714

You're not waiting for them to complete. You need to call producer.each(&:join). producer.join is calling join on the array

Upvotes: 2

Related Questions