perl多线程问题的自动增量

时间:2014-08-18 16:23:24

标签: perl

我正在编写多线程perl脚本并将输出存储在csv文件中。我试图插入一个名为sl.no的字段。在输入的每一行的csv文件中,但是当我使用线程时,sl。没有。在大多数情况下重叠。以下是我的代码段的概念。

for ( my $count = 1 ; $count <= 10 ; $count++ ) {
    my $t = threads->new( \&sub1, $count );
    push( @threads, $t );
}

foreach (@threads) {
    my $num = $_->join;
}

sub sub1 {
    my $num = shift;

    my $start = '...';    #distributing data based on an internal logic
    my $end   = '...';    #distributing data based on an internal logic
    my $next;

    for ( my $x = $start ; $x <= $end ; $x++ ) {
        my $count = $x + 1;

        #part of code from which I get @data which has name and age

        my $j = 0;
        if ( $x != 0 ) {
            $count = $next;
        }
        foreach (@data) {
            #j is required here for some extra code
            flock( OUTPUT, LOCK_EX );
            print OUTPUT $count . "," . $name . "," . $age . "\n";
            flock( OUTPUT, LOCK_UN );
            $j++;
            $count++;

        }
        $next = $count;
    }

    return $num;
}

我需要递增计数,这是将插入csv文件的行的序列号。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

你会想做这样的事情:

use threads;
use threads::shared;

my $counter :shared;
$counter = 1;

sub nextValue() {
  lock $counter;
  return $counter++;
}

然后只需在代码中调用nextValue()即可。这将确保一次只有一个线程增加共享计数器。

答案 1 :(得分:1)

您已经使用flock提供了互斥功能,因此,如果它是唯一使用$count的地方,也可以利用它。

my $counter :shared;  # Once for all threads
for (@data) {
    ...
    flock( OUTPUT, LOCK_EX );
    print OUTPUT ++$count . "," . $name . "," . $age . "\n";
    flock( OUTPUT, LOCK_UN );
 }

或者我们可以切换到只使用Perl锁。

my $counter :shared;  # Once for all threads
for (@data) {
    ...
    {
       lock $counter;
       print OUTPUT ++$count . "," . $name . "," . $age . "\n";
    }
 }

在这两种情况下,输出文件中的行都是数字顺序。