0

I use the Parallel::ForkManager module for fetching some pages. Below is the relevant code snippet:

use Parallel::ForkManager;

open FILE,">myfile" or die "cann't open file$!";
$pm = new Parallel::ForkManager(5);

foreach $data (@all_data) {

    my $pid = $pm->start and next;
    #doing the fetching here and get the result on parsed_string

    print FILE $parsed_string;
    $pm->finish; # Terminates the child process
}

Could someone expain why the results are OK and don't overlap one with the other even there is more than one process writing to the same File ?

7
  • Please format your code as code by putting 4 spaces at the front of each line.
    – Jonathan M
    Jul 21, 2011 at 22:38
  • In this code sample, you are opening a filehandle in read (<) mode and then print'ing to it. Is that what you meant to say?
    – mob
    Jul 21, 2011 at 22:50
  • I mean opening the file for write on the parent proccess(i don't able to edit my question any more) and print to the file on the child processes
    – Rubin
    Jul 21, 2011 at 22:56
  • Because&nbsp;you are&nbsp;lucky.
    – mob
    Jul 22, 2011 at 0:23
  • 1
    If you want to be sure of no overlap, open the file in the child process and use flock().
    – runrig
    Jul 22, 2011 at 14:21

2 Answers 2

2

Give it something to race. Printing a single line doesn't create a resource contention. Does the output from this program do more of what you expect?

use Parallel::ForkManager;

open FILE, '>', 'myfile' or die "cann't open file$!";
select FILE; $|++;

my $pm = Parallel::ForkManager->new(5);

foreach $data ( 0 .. 100 ) {
    my $pid = $pm->start and next;
    #doing the fetching here and get the result on parsed_string

    print FILE "1. ";
    sleep 1;
    print FILE "Printing from ";
    sleep int( rand 3 );
    print FILE "$$\n";
    sleep int( rand 5 );
    print FILE "2. Print";
    sleep int( rand 2 );
    print FILE "ing from $$\n";
    $pm->finish;
}

I got:

1. 1. 1. 1. 1. Printing from 7515
Printing from Printing from 7517
Printing from Printing from 7519
2. Print7518
2. Print7516
ing from 7517
1. ing from 7515
2. Printing from 7519
1. Printing from 1. Printing from 7520
2. PrintPrinting from 7522
2. Print2. Print7521
ing from 7520
1. ing from 7516
ing from 7518
1. 2. Print1. 2. Printing from 7522
1. Printing from Printing from ing from 7521
Printing from 1. Printing from 7527
7524
2. Print7525
2. Printing from 7525
7526
1. Printing from ing from 7524
1. 2. Print from 
0

Because you are lucky.

1
  • To those of you who keep flagging this answer: it is correct, if a bit terse. Suggest downvoting if you don't like the way it was presented; two mods have looked at the answer already and deemed it acceptable. Jul 23, 2011 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.