I can't comment on which is better (fork/threads), but here's an example using Parallel::ForkManager that I wrote a while ago for someone else.

I've modified it a bit to suit your requirements. First, $max_forks specifies the maximum number of forks to run at a time. Next, I create an array of 1000 elements. Then in the while(), I splice out 200 elements of the @array into a new array, and fork out to db_save() with that array slice, simulating your desire to only do a specific number of items per fork().

#!/usr/bin/perl use warnings; use strict; use Parallel::ForkManager; my $max_forks = 3; my $fork = new Parallel::ForkManager($max_forks); my @array = (1..1000); # on start callback $fork->run_on_start( sub { my $pid = shift; } ); # on finish callback $fork->run_on_finish( sub { my ($pid, $exit, $ident, $signal, $core) = @_; if ($core){ print "PID $pid core dumped.\n"; } } ); # forking code while (@array){ my @chunk = splice @array, 0, 200; $fork->start and next; sleep(2); db_save(@chunk); $fork->finish; } sub db_save { my @a = @_; print "$a[1]\n"; } $fork->wait_all_children;

In reply to Re: Fork or Thread? by stevieb
in thread Fork or Thread? by beanscake

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.