Ruby - how do I run a method on each array element on different threads? Ruby - how do I run a method on each array element on different threads? arrays arrays

Ruby - how do I run a method on each array element on different threads?


It sounds like you want something like a pmap function. There is a ruby library called peach that provides both a pmap and a peach ("parallel" each) method on the native arrays.

With this library, you can do something like

require 'peach'[1,2,3,4].pmap{|x| f(x)} #Spawns 4 threads, => [f(1),f(2),f(3),f(4)]


There are many ways to achieve concurrency, and using threads is one way. However, the best performance depends on the Ruby runtime you choose.

For example, one simple way to multithread is the 'peach' (parallel each) library http://peach.rubyforge.org/. However, this works best on JRuby, which uses native threads.

For the MRI runtime you may want to use multiple processes like DRb or a message bus like RabbitMQ.

For a great writeup on the many options, see this post: http://merbist.com/2011/02/22/concurrency-in-ruby-explained/


If I properly understand, you need something like this snippet:

foo = %w{1 2 3}  # => ["1", "2", "3"]# in your case it would be some time-consumed operation on stringdef inc(element)  element.succend  # => nil inc("1")  # => "2" threads = foo.map do |f|  Thread.new { inc(f) }end# => [#<Thread:0x8d28694 run>, #<Thread:0x8d28630 run>, #<Thread:0x8d28590 run>] threads.map { |t| t.value }  # => ["2", "3", "4"]