From: Jason Mayer Date: 2006-11-25T22:11:54+09:00 Subject: Re: newbie question regarding threads and system commands ------=_Part_74788_12594035.1164460311563 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Maybe there's something wrong with my system here at work then.... because this took 11.something seconds to run on my machine. I'll test again from home (both xp pro systems) On 11/24/06, Edwin Fine wrote: > > This is one possible solution, which seems to work fine (it takes 3.14 > seconds on my system to ping 3 web sites). Bottom line: you need to keep > a list of the threads and join all of them in the calling code. Hope > this helps. I recommend that you get a copy of the "Pickaxe" book > (Programming Ruby: The Pragmatic Programmers Guide, 2nd edition) , which > has a very good section on threading and lots of examples. In the > meantime, you can read this from the first edition: > > http://www.rubycentral.com/book/tut_threads.html > ------------- > require 'thread' > > class SystemExecutor > # Returns array [[cmd, response], [cmd, response], ...] > def SystemExecutor.run(system_cmd_list) > thread_list = [] > system_response_list = [] > srl_mutex = Mutex.new > > system_cmd_list.each do |cmd| > thread_list << Thread.new do > begin > response = %x{ #{cmd} } > srl_mutex.synchronize do > system_response_list << [cmd, response] > end > rescue Exception => exc > srl_mutex.synchronize do > system_response_list << [cmd, exc] > end > end > end > end > > thread_list.each { |thr| thr.join } > system_response_list > end > end > > puts "Starting ping" > start_time = Time.now > resp = SystemExecutor.run(['ping www.ruby-forum.org', 'ping > www.sourceforge.net', 'ping www.google.com']) > elapsed_time = Time.now - start_time > > resp.each do |cmd, resp| > puts "Command: #{cmd}", '-' * 20 > puts "Response:\n", '-' * 20, "#{resp}" > end > > puts "Elapsed time: #{elapsed_time} seconds." > > -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_74788_12594035.1164460311563--