Running methods in parallel

S

Skave Rat

is there a way to parallelize ruby methods?

So I can do something like this:
------------
5.times do
Foobar.new("somestuff")
end

#do stuff while Foobar-objects are running

------


so the script creates 5 objects, and just lets them do their job, while
running the rest of the code.



meh, I really hope you understand what i mean ;)
 
P

Phlip

You can always use threads:

Threads are often a patch over bad architecture. You can also try this:

foobars = (0..5).map{ Foobar.new("somestuff") }

loop do
foobars.each{|foobar| foobar.run_one_slice }
end

Whatever foobar does, it must use some loop statement. If you put the loop on
the outside, you will have a better architecture. Each call to run_one_slice
performs one foobar activity. Foobar must store its state as instance variables,
between each call to .run_one_slice. That forces Foobar to be more
object-oriented, and more event-driven.

If you start with a good architecture, and measure it, you will know if its
performance is adequate, or if it needs more help. Only then you add threads.
And threads work best with event-driven architectures, so adding the thread last
is always better than adding it first. Premature optimization is the root of all
evil.
 
E

Erik Veenstra

[Note: parts of this message were removed to make it a legal post.]
is there a way to parallelize ruby methods?

Have a look at ForkAndReturn [1,2]. ForkAndReturn implements a
couple of methods that simplify running a block of code in a
subprocess. The result (Ruby object or exception) of the block
will be available in the parent process.

Here's an example:

[1, 2, 3, 4].concurrent_collect do |object|
2*object
end # ===> [2, 4, 6, 8]

This runs each "2*object" in a seperate process. Hopefully, the
processes are spread over all available CPU's.

gegroet,
Erik V. - http://www.erikveen.dds.nl/

[1] http://www.erikveen.dds.nl/forkandreturn/doc/index.html
[2] http://rubyforge.org/projects/forkandreturn/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,662
Latest member
sxarexu

Latest Threads

Top