(new to ruby)

I have a routine that makes a web call then does some work. I need to do
many of these, and because of latency and all that, I want to go ahead
and spawn several of these in async "tasks" (trying to avoid key words
like processes and threads). I need to collect the results of each task.

So, generically, let's say I have a TaskManager and a Task. TaskManager
is initialized with an array of elements to process. Each element is
passed to a Task for processing. I want several Tasks processing in
parallel, and the result from each Task must get reported back to
TaskManager.

I see Ruby threads is one way, and despite the disparaging commens I see
about them, they're probably fine for me to get started with to figure
out the "feedback" mechanisms, but eventually I do need a method which
is capable of leveraging multi-core machines.

Using the pickaxe book Multithreading chapter, I've put together this
little outline, but the results always come back in order when I believe
useing sleep should randomize them, so I'm suspicioius that I'm not
really getting async processing out of my code.

#! /usr/local/bin/ruby

class TaskManager

  attr_reader :results

  def manageTasks
    taskList = ['one', 'two', 'three']
    threads = []
    @results = []
    indx = 0

    taskList.each do |taskParam|
      threads[indx] = Thread.new do
        thisTask = Task.new
        @results[indx] = thisTask.doStuff(taskParam)
      end
      indx += 1
    end

    threads.each {|thred| thred.join}
  end
end

class Task
  def doStuff(taskParam)
    pause = ((rand(0.1))*4)
    sleep pause
    return ('handing back ' + taskParam + ', ' + pause.to_s)
  end
end

taskMngr = TaskManager.new
taskMngr.manageTasks
puts taskMngr.results

Looking for hints as to what I am doing wrong.

Can anyone point me to a tutorial using a technique that will use
multi-core CPUs?

Many thanks.

-- gw
-- 
Posted via http://www.ruby-forum.com/.