0

我使用该Parallel::ForkManager模块来获取一些页面。下面是相关的代码片段:

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
}

有人可以解释为什么结果是好的并且即使有多个进程写入同一个 File 也不会与另一个重叠?

4

2 回答 2

2

给它一些比赛的东西。打印单行不会产生资源争用。该程序的输出是否符合您的预期?

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;
}

我有:

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 
于 2011-07-23T10:58:46.673 回答
0

因为你很幸运。

于 2011-07-22T00:23:34.317 回答