Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

So I have an array of 40000 elements, and I wish to run a method on each element.

To reduce the time it will take, I am thinking of running this on multiple threads. Perhaps splitting the array into multiple arrays and running on a different thread or something. But I don't know how to get started.

Say the array is foo[], and the method to call is bar(). bar() returns a string. After the code executes, I want to be able to combine/add up all the strings together in one big string.

Is there a way to do this? I tried to keep my question as simple as possible, but if you want more information, let me know.

Thanks in advance!

like image 758
Gbert90 Avatar asked Nov 05 '11 22:11

Gbert90


1 Answers

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)]
like image 170
Damon Snyder Avatar answered Oct 19 '22 16:10

Damon Snyder