From: 7stud -- Date: 2007-10-07T20:31:52+09:00 Subject: Re: Multitasking and collecting results Greg Willits wrote: > Greg Willits wrote: >> 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. > > Oh wait, they're in order because that's the order I have them inserted > into @results. Duh. > > I confirmed async by putting a timer wrapper around the whole thing, and > indeed it completes in less time than the sum of each task's pause time. > Try the following to see some random order in the results. The threads in the code enter their data in a Queue (located in the 'thread' module in the Standard Library). A Queue enables you to pass data between threads in a "thread-safe manner". A "thread safe manner" means that only one thread can access the Queue at the same time. A Queue guarantees that two threads can't access the Queue at the same time, so the data cannot get scrambled. require 'thread' class TaskManager attr_reader :results def initialize(*task_params) @task_params = task_params @results = Queue.new end def start_producers threads = [] @task_params.each_with_index do |param, indx| threads[indx] = Thread.new do @results << Task.new.do_stuff(param) end end threads.each {|thred| thred.join} end end class Task def do_stuff(x) pause = rand() * 4 sleep pause "handing back #{x}, #{pause}" end end task_mngr = TaskManager.new('one', 'two', 'three') task_mngr.start_producers num_results = task_mngr.results.length num_results.times {puts task_mngr.results.pop} Note that rand(.1) is the same as rand(), so I don't know why pickaxe2 uses rand(.1). -- Posted via http://www.ruby-forum.com/.