当我的进程写入文件时,为什么我看不到竞争条件?

时间:2011-07-21 22:35:20

标签: perl cpan

我使用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
}

即使有多个进程写入同一个文件,有人可能会说明为什么结果没问题并且不与其他进程重叠?

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:0)

因为你很幸运。