From: Rick DeNatale Date: 2007-09-06T12:17:16+09:00 Subject: Re: Ruby Threads question On 9/5/07, Cd Cd wrote: > The following code is a slight modification of the code found at the top > of page 136 in the book "Programming Ruby The Pragmatic Programmers' > Guide" by Dave Thomas with Chad Fowler and Andy Hunt > > #!/usr/bin/ruby -w > > require 'net/http' > > pages = %w(www.google.com www.slashdot.org www.mit.edu) > threads = [] > > for page_to_fetch in pages > threads << Thread.new(page_to_fetch) do |url| > h=Net::HTTP.new(url, 80) > puts "Fetching: #{url}" > resp = h.get('/', nil) > puts "Got #{url}: #{resp.message}" > end > end > > threads.each {|thr| thr.join } > > How come when I run this code, the following output goes line by line? > Fetching: www.google.com > Fetching: www.slashdot.org > Fetching: www.mit.edu > Got www.slashdot.org: Moved Permanently > Got www.google.com: OK > Got www.mit.edu: OK > > > Shouldn't the output be all done at once since the code is running in > parallel? I'm not sure what you mean "all done at once". If the code wasn't running in parallel threads then I'd expect to see: Fetching: www.google.com Got www.google.com: OK Fetching: www.slashdot.org Got www.slashdot.org: Moved Permanently Fetching: www.mit.edu Got www.mit.edu: OK What's really happening is something like: Thread 1 Thread 2 Thread 3 opens HTTP prints Fetching:www.google.com issues get opens http prints Fetching: www.slashdot.org issues get prints Fetching: www.mit.edu issues get get finishes prints Got www.slashdot.org: Moved Permanently get finishes prints Got www.google.com: OK get finishes prints Got www.mit.edu: OK So the output order is evidence that there is indeed parallel activity. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/