Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Parallel ForkManager

by tirwhan (Abbot)
on Apr 07, 2010 at 08:30 UTC ( #833224=note: print w/ replies, xml ) Need Help??


in reply to Parallel ForkManager

To further expand on the two (perfectly correct and valid) comments by almut and moritz above, here is a script that does exactly what you asked for:

#!/usr/bin/perl use warnings; use strict; use Parallel::ForkManager; use Sys::CPU; my $number_of_cpus = Sys::CPU::cpu_count(); my $pm = new Parallel::ForkManager($number_of_cpus); for (1..$number_of_cpus) { my $pid = $pm->start and next; my $string="abcdefg"; my $ln=length($string); print "length of a string = $ln \n"; $pm->finish(); }

This uses Sys::Cpu to find the number of CPUs the system has, then forks off that number of processes and executes the code in them. Note you'll get the output ("length of a string...") multiple times (depending on the number of processors you have in the system), because exactly the same code is run in each process. So this approach is rather nonsensical, it uses all processors (normally, depends on your OS) but simply multiplies the workload. Something more sensible would be to have each child measure a different string, e.g.:

#!/usr/bin/perl use warnings; use strict; use Parallel::ForkManager; use Sys::CPU; my $number_of_cpus = Sys::CPU::cpu_count(); my $pm = new Parallel::ForkManager($number_of_cpus); my @strings = ("abcde","abcdefghij","ab"); for (1..scalar @strings) { my $pid = $pm->start and next; my $string=$strings[$_-1]; my $ln=length($string); print "length of string \"$string\" = $ln \n"; $pm->finish(); }

This will hand each child a different string and thus "parallelize" the work done. This is slightly less senseless than the previous example, but only slightly, because the work done by your machine to fork off a separate process is much more than the simple act of measuring the length of a string. So, as the previous commenters have already pointed out, you need to do some thinking on exactly what you want to parallelize and how to do it in a worthwhile fashion. Anyway, hope this helps clear up some confusion.


All dogma is stupid.


Comment on Re: Parallel ForkManager
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://833224]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (13)
As of 2014-11-24 20:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (147 votes), past polls