问题描述:

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 ?

网友答案:

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 
网友答案:

Because you are lucky.

相关阅读:
Top