tags:

views:

80

answers:

1

is it more efficient to run multiple instances of a ruby script ? or multiple threads within that single script ?

take for example, a ruby script to check all links of a given domain are working.

would you run multiple instance of this script or multiple threads ?

how do you create multiple threads ?

+2  A: 

"Efficiency" could mean many things. For Ruby < 1.9, the green threads mean that you won't get as much concurrency as you might think out of threads, so using multiple script instances would be the best way to minimize total real time from start to finish.

As to creating them, here is the Pickaxe book example of downloading pages "in parallel":

require 'net/http'


pages = %w( www.rubycentral.com
            www.awl.com
            www.pragmaticprogrammer.com
           )


threads = []


for page in pages
  threads << Thread.new(page) { |myPage|


    h = Net::HTTP.new(myPage, 80)
    puts "Fetching: #{myPage}"
    resp, data = h.get('/', nil )
    puts "Got #{myPage}:  #{resp.message}"
  }
end


threads.each { |aThread|  aThread.join }
DigitalRoss
im not sure what the threads.each is for in the end.
gpwu
It waits until the threads are finished, so (a) you can safely use the results, and (b) you don't want to exit if you have threads doing something important. (They go poof at kernel#exit.)
DigitalRoss