Forum: Ruby ruby threads

Posted by Vlad Smith (neverhood)
on 2009-07-01 22:43
Hi guys! Hope you`ll find some time to assist with any ideas

i have an array of links and a number of steps that needs to be done to
each of those links.

there are always the same amount of links in array..so basically i can
do everything manually

i was wondering how can i create the new thread for processing each of
those links , maybe there`s a way of doing something like this :

array.each do |link|
  a = Thread.new {....}
  a.join
end
Posted by Justin Collins (Guest)
on 2009-07-01 23:16
(Received via mailing list)
Vlad Smith wrote:
>
> array.each do |link|
>   a = Thread.new {....}
>   a.join
> end
>   

That almost works, except it will block on each thread before starting
the next.

threads = []

array.each do |link|
  threads << Thread.new {....}
end

threads.each do |t|
   t.join
end


-Justin
Posted by Aaron Patterson (Guest)
on 2009-07-01 23:17
(Received via mailing list)
On Thu, Jul 02, 2009 at 05:44:00AM +0900, Vlad Smith wrote:
> 
> array.each do |link|
>   a = Thread.new {....}
>   a.join
> end

Your code won't run anything in parallel.  Thread#join will wait until
the thread is finished.

Try mapping your array to a list of threads, then iterating over that
list calling join:

  array.map { |link|
    Thread.new(link) { |l| ... }
  }.each { |thread| thread.join }
Posted by Vlad Smith (neverhood)
on 2009-07-03 09:45
thanks everybody, works works just great!
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.